Home  >  Article  >  Backend Development  >  How Can I Return Multiple Values from a Python Function?

How Can I Return Multiple Values from a Python Function?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-20 19:32:15292browse

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()

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)

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}

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!

Statement:
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