Search code examples
pythoniterable-unpacking

Breaking down the loop logic for the below code:


I am trying to understand the below code but I am unable to get the loop section

I am new to unpacking

records = [('foo',1,2),('bar','hello'),('foo',3,4)]
def do_foo(x,y):
    print('foo',x,y)

def do_bar(s):
    print('bar',s)

for tag, *args in records:
    if tag == 'foo':
        do_foo(*args)
    elif tag == 'bar':
        do_bar(*args)

Solution

  • records is a tuple -> ('foo', 1, 2)

    The for-loop there uses multiple iteration variables tag, *args. This means that the tuple is unpacked - i.e expanded into its constituents.

    tag -> asks for one element from this tuple, it gets foo.

    *args -> asks for all the rest of the elements from the tuple - as a tuple. It gets (1,2) : this is packing

    Now do_foo(x,y) is a normal function. it's being called like this do_foo(*args). Remember args is now (1,2).

    *args -> *(1,2) -> 1,2 : The tuple is unpacked - due to the *. The expression ends up being do_foo(1,2) - which fits our function signature!

    In summary, in the for-loop tag, *args, the *args is used for asignment -which packs stuff into a tuple. In the function call, the *args is used as argument - which unpacks stuff into function call arguments.