0

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)
Wesam
  • 932
  • 3
  • 15
  • 27
  • You could start by reading the [documentation](https://docs.python.org/3.7/tutorial/controlflow.html#unpacking-argument-lists). – Jacques Gaudin Apr 03 '19 at 12:25

2 Answers2

0
records = [('foo',1,2),('bar','hello'),('foo',3,4)]
def do_foo(x,y):
    #This function takes two arguments
    print('foo',x,y)

def do_bar(s):
    #This function takes one argument
    print('bar',s)

for tag, *args in records:
    #Here we are looping over the list of tuples.
    #This tuple can have 2 or 3 elements
    #While looping we are getting the first element of tuple in tag,
    # and packing rest in args which can have 2 or 3 elements
    if tag == 'foo':
        #do_foo requires 2 arguments and when the first element is foo, 
        # as per the provided list tuple is guaranteed to have total 3 elements,
       # so rest of the two elements are packed in args and passed to do_foo
        do_foo(*args)
    elif tag == 'bar':
       #Similarly for do_bar
        do_bar(*args)

I suggest for better understanding, you can read the documentation.

Ashish
  • 4,206
  • 16
  • 45
0

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.

rdas
  • 20,604
  • 6
  • 33
  • 46