4

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:

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

func('a', 'b', 3, 'something')

But what I want to do is this:

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

And this should behave similar to the first case. I think I should use here reprint and eval but not sure how exactly.

I know that I can just pass the tuple in the function and then unpack it within the body, but my question here is how to unpack it in the function call itself.

tobias_k
  • 81,265
  • 12
  • 120
  • 179
Kris
  • 67
  • 1
  • 1
  • 4

3 Answers3

3

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:

>>> def func2(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.

tobias_k
  • 81,265
  • 12
  • 120
  • 179
1

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])
>>>
>>> def func(*args):
...  for arg in args:
...   print(arg)
...
>>>
>>> func(*MyTuple)
one
2
[3]
>>>
>>> func(MyTuple)
('one', 2, [3])
mencucci
  • 180
  • 1
  • 10
1

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 = 4
i = something-else
Dikshit Kathuria
  • 1,182
  • 12
  • 15