This is probably a dumb question, but I couldn't find anything from searches.
I know if I want to unpack a returned tuple into multiple variables, the syntax is A,B = myfunction()
What if my function is returning a tuple of lists, such as ( [1], [2] )
, and I want to assign to my variables integer 1
and 2
instead of the lists [1]
and [2]
? Is there a shorthand one liner for this or do I need to do
A, B = myfunction()
A = A[0]
B = B[0]
Thanks in advance for your help.
Use the same structure:
[A], [B] = myfunction()
Demo:
>>> def myfunction():
return ( [1], [2] )
>>> [A], [B] = myfunction()
>>> A
1
>>> B
2
Regarding DeepSpace's comment that "this creates 2 new lists": It doesn't:
>>> import dis
>>> dis.dis('[A], [B] = myfunction()')
1 0 LOAD_NAME 0 (myfunction)
2 CALL_FUNCTION 0
4 UNPACK_SEQUENCE 2
6 UNPACK_SEQUENCE 1
8 STORE_NAME 1 (A)
10 UNPACK_SEQUENCE 1
12 STORE_NAME 2 (B)
14 LOAD_CONST 0 (None)
16 RETURN_VALUE
This is what creating a list looks like:
>>> dis.dis('[A]')
1 0 LOAD_NAME 0 (A)
2 BUILD_LIST 1
4 RETURN_VALUE
Context matters.
Use arguments so you can control the indexing from outside.
def myfunction(a_index=None, b_index=None):
...
if a_index is None and b_index is None:
return a, b
return a[a_index], b[b_index]
Then
A, B = myfunction(0, 0)
This is a reusable solution. If you ever need other indexes:
A, B = myfunction(2, 1)
This does not support mixing (ie only passing a_index
or b_index
) but if you need that behavior you can easily add it.
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