Skip to content Skip to sidebar Skip to footer

Passing A Tuple In *args

I'd like to pass a tuple (or maybe a list) to a function as a sequence of values (arguments). The tuple should be then unpacked as an argument into *arg. For example, this is clear

Solution 1:

You can just use func(*tup) to unpack the tuple directly when you invoke the function.

>>> func(*tup)
i =  a1
i =  a2
i =  4
i =  something-else

This is kind of equivalent to func(tup[0], tup[1], tup[2], ...). The same also works if the function expects multiple individual parameters:

>>>deffunc2(a, b, c, d):...print(a, b, c, d)...>>>func2(*tup)
('a1', 'a2', 4, 'something-else')

See e.g. here for more in-depth background on the syntax.

Solution 2:

You can unpack the tuple during the call by putting a * before the identifier of the tuple. This allows you to easily differentiate between tuples that should be unpacked and ones which shouldn't. This is an example:

>>>MyTuple = ('one', 2, [3])>>>>>>deffunc(*args):...for arg in args:...print(arg)...>>>>>>func(*MyTuple)
one
2
[3]
>>>>>>func(MyTuple)
('one', 2, [3])

Solution 3:

You can use *args if you want to unpack your tuple. Your method definition goes as follows :

def func(*tup):
    for i in tup:
        print(print"i = ",i)

Now calling your method:

tup = ('a1','a1',4,'something-else') 
func(*tup)

Which will yield you the output as-

i = a1
i = a2
i = 4i = something-else

Post a Comment for "Passing A Tuple In *args"