How to Return Two Values from a Function in Python

How can I return two values from a function in Python?

You cannot return two values, but you can return a tuple or a list and unpack it after the call:

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

my_i, my_card = select_choice()

On line return i, card i, card means creating a tuple. You can also use parenthesis like return (i, card), but tuples are created by comma, so parens are not mandatory. But you can use parens to make your code more readable or to split the tuple over multiple lines. The same applies to line my_i, my_card = select_choice().

If you want to return more than two values, consider using a named tuple. It will allow the caller of the function to access fields of the returned value by name, which is more readable. You can still access items of the tuple by index. For example in Schema.loads method Marshmallow framework returns a UnmarshalResult which is a namedtuple. So you can do:

data, errors = MySchema.loads(request.json())
if errors:
...

or

result = MySchema.loads(request.json())
if result.errors:
...
else:
# use `result.data`

In other cases you may return a dict from your function:

def select_choice():
...
return {'i': i, 'card': card, 'other_field': other_field, ...}

But you might want consider to return an instance of a utility class (or a Pydantic/dataclass model instance), which wraps your data:

class ChoiceData():
def __init__(self, i, card, other_field, ...):
# you can put here some validation logic
self.i = i
self.card = card
self.other_field = other_field
...

def select_choice():
...
return ChoiceData(i, card, other_field, ...)

choice_data = select_choice()
print(choice_data.i, choice_data.card)

How to return two values from a function and then use both of them as parameters within the parameter of another function as two parameters

Here it is a function that returns a tuple

def return_ab():
return 5, 6

Here it is a function that accepts three arguments

def test(a, b, c):
print(a, b, c)

And here it is how you can call the test() function passing it the two parameters returned by return_ab() but unpacked

test(*return_ab(), 7) # => 5 6 7

The key point is the asterisk in front of return_ab(). It's a relatively new syntax that is very useful indeed...

How does Python return multiple values from a function?

Since the return statement in getName specifies multiple elements:

def getName(self):
return self.first_name, self.last_name

Python will return a container object that basically contains them.

In this case, returning a comma separated set of elements creates a tuple. Multiple values can only be returned inside containers.

Let's use a simpler function that returns multiple values:

def foo(a, b):
return a, b

You can look at the byte code generated by using dis.dis, a disassembler for Python bytecode. For comma separated values w/o any brackets, it looks like this:

>>> import dis
>>> def foo(a, b):
... return a,b
>>> dis.dis(foo)
2 0 LOAD_FAST 0 (a)
3 LOAD_FAST 1 (b)
6 BUILD_TUPLE 2
9 RETURN_VALUE

As you can see the values are first loaded on the internal stack with LOAD_FAST and then a BUILD_TUPLE (grabbing the previous 2 elements placed on the stack) is generated. Python knows to create a tuple due to the commas being present.

You could alternatively specify another return type, for example a list, by using []. For this case, a BUILD_LIST is going to be issued following the same semantics as it's tuple equivalent:

>>> def foo_list(a, b):
... return [a, b]
>>> dis.dis(foo_list)
2 0 LOAD_FAST 0 (a)
3 LOAD_FAST 1 (b)
6 BUILD_LIST 2
9 RETURN_VALUE

The type of object returned really depends on the presence of brackets (for tuples () can be omitted if there's at least one comma). [] creates lists and {} sets. Dictionaries need key:val pairs.

To summarize, one actual object is returned. If that object is of a container type, it can contain multiple values giving the impression of multiple results returned. The usual method then is to unpack them directly:

>>> first_name, last_name = f.getName()
>>> print (first_name, last_name)

As an aside to all this, your Java ways are leaking into Python :-)

Don't use getters when writing classes in Python, use properties. Properties are the idiomatic way to manage attributes, for more on these, see a nice answer here.

How to annotate types of multiple return values?

You are always returning one object; using return one, two simply returns a tuple.

So yes, -> Tuple[bool, str] is entirely correct.

Only the Tuple type lets you specify a fixed number of elements, each with a distinct type. You really should be returning a tuple, always, if your function produces a fixed number of return values, especially when those values are specific, distinct types.

Other sequence types are expected to have one type specification for a variable number of elements, so typing.Sequence is not suitable here. Also see What's the difference between lists and tuples?

Tuples are heterogeneous data structures (i.e., their entries have different meanings), while lists are homogeneous sequences. Tuples have structure, lists have order.

Python's type hint system adheres to that philosophy, there is currently no syntax to specify an iterable of fixed length and containing specific types at specific positions.

If you must specify that any iterable will do, then the best you can do is:

-> Iterable[Union[bool, str]]

at which point the caller can expect booleans and strings in any order, and of unknown length (anywhere between 0 and infinity).

Last but not least, as of Python 3.9, you can use

-> tuple[bool, str]

instead of -> Tuple[bool, str]; support for type hinting notation has been added to most standard-library container types (see PEP 585 for the complete list). In fact, you can use this as of Python 3.7 too provided you use the from __future__ import annotations compiler switch for your modules and a type checker that supports the syntax.

Python : How to return two values from function which is called from elif?

You can try:

def some_function(correct):
if correct:
return False
else:
return False

def someother_function():
if correct:
return True, f
else:
return False, None

if some_function():
print("something")
elif [x := someother_function()] and x[0]:
print(x[1])
else:
print("nothing")

Return multiple values from function

Dart doesn't support multiple return values.

You can return an array,

List foo() {
return [42, "foobar"];
}

or if you want the values be typed use a Tuple class like the package https://pub.dartlang.org/packages/tuple provides.

See also either for a way to return a value or an error.

how to return multiple values from a function and use that in somewhere else in python programme

functions can only return a single value.

It's easy to pack multiple values into a tuple and return that

def f(x, y):
retval1 = x + y
retval2 = x * y
return retval1, retval2

You can unpack the returned tuple like this

sumval, prodval = f(5,7)


Related Topics



Leave a reply



Submit