6

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?

1 Answer 1

9

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.