Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

concise way to unpack twice from returned

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.

like image 829
Clara Avatar asked Jan 25 '23 08:01

Clara


2 Answers

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.

like image 185
Kelly Bundy Avatar answered Jan 30 '23 12:01

Kelly Bundy


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.

like image 27
DeepSpace Avatar answered Jan 30 '23 14:01

DeepSpace