Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return two variables from a python function and access its values without calling it two times?

Tags:

python

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?

like image 736
Mike B Avatar asked May 02 '19 19:05

Mike B


People also ask

Can you return 2 variables in Python?

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.

How do I store two values returned from a function?

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.

How do you return a variable from a function in Python?

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.

Can a method have 2 return?

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.


1 Answers

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)
like image 95
wim Avatar answered Nov 15 '22 00:11

wim