How Can I Return Multiple Values from a Python Function?

Patricia Arquette
Release: 2024-11-20 19:32:15
Original
291 people have browsed it

How Can I Return Multiple Values from a Python Function?

Returning Multiple Values from Functions in Python

In Python, functions typically return a single value. However, in certain scenarios, you may need to return multiple values.

To return more than one value from a function, you cannot simply use multiple return statements. Instead, there are several techniques you can consider:

Tuples and Lists:

One option is to return a tuple or a list containing the values you want to return. You can then unpack the tuple or list after the function call. For instance:

def select_choice():
    # ... previous code here
    return i, card  # or [i, card]

my_i, my_card = select_choice()
Copy after login

By returning a tuple or list, the returned values are stored in separate variables.

Named Tuples:

If you plan on returning more than two values, consider using a named tuple. This allows you to access the returned values by their named attributes, enhancing readability.

from collections import namedtuple

ChoiceData = namedtuple('ChoiceData', 'i card other_field')

def select_choice():
    # ... previous code here
    return ChoiceData(i, card, other_field)

choice_data = select_choice()

# access values via attributes
print(choice_data.i, choice_data.card)
Copy after login

Dictionaries:

Returning a dictionary is also possible, allowing you to name the returned values and access them by their keys:

def select_choice():
    # ... previous code here
    return {'i': i, 'card': card, 'other_field': other_field}
Copy after login

Custom Utility Classes:

For more complex scenarios, consider creating a utility class or a Pydantic/dataclass model instance to wrap your returned data, offering validation and encapsulation.

By understanding these techniques, you can effectively return multiple values from functions in Python, enhancing the flexibility and usability of your code.

The above is the detailed content of How Can I Return Multiple Values from a Python Function?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template