Suppose I have the following function:
def f():
return [1,2,3], [4,5,6]
I can call this function successfully like below:
a,b = f()
print(a,b) #prints [1, 2, 3] [4, 5, 6]
But suppose that I want to have access only to the first item (1) of the first list and the first item (4) of the second list. To do that I call it like below successfully:
a,b = f()[0][0], f()[1][0]
print(a,b) #prints 1 4
I do not control function f()
as it is written in a library.
Is it possible in Python to do the last operation, without calling the function two times and without using the returned a and b values?
Python functions can return multiple variables. These variables can be stored in variables directly. A function is not required to return a variable, it can return zero, one, two or more variables. This is a unique property of Python, other programming languages such as C++ or Java do not support this by default.
To return multiple values from a function in Python, return a tuple of values. A tuple is a group of comma-separated values. You can create a tuple with or without parenthesis. To access/store the multiple values returned by a function, use tuple destructuring.
The Python return statement is a special statement that you can use inside a function or method to send the function's result back to the caller. A return statement consists of the return keyword followed by an optional return value. The return value of a Python function can be any Python object.
You can't return two values. However, you can return a single value that is a struct that contains two values. Show activity on this post. You can return only one thing from a function.
Using an extended unpacking assignment:
>>> def f():
... return [1,2,3], [4,5,6]
...
...
>>> [a0, *rest], [b0, *rest] = f()
>>> a0, b0
(1, 4)
Using zip-splat trick:
>>> next(zip(*f()))
(1, 4)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With