Paul Manta
Paul Manta

Reputation: 31567

How to unpack multiple tuples in function call

If I have a function def f(a, b, c, d) and two tuples, each with two elements, is there any way to unpack these tuples so that I can send their values to the function?

f(*tup1, *tup2)

Upvotes: 22

Views: 12089

Answers (2)

Gareth Latty
Gareth Latty

Reputation: 88987

As of the release of Python 3.5.0, PEP 448 "Additional Unpacking Generalizations" makes the natural syntax for this valid Python:

>>> f(*tup1, *tup2)
1 2 2 3

In older versions of Python, you can need to concatenate the tuples together to provide a single expanded argument:

>>> tup1 = 1, 2
>>> tup2 = 2, 3
>>> def f(a, b, c, d):
        print(a, b, c, d)

>>> f(*tup1+tup2)
1 2 2 3

Upvotes: 25

jamylak
jamylak

Reputation: 133544

Another approach using chain

>>> from itertools import chain
>>> def foo(a,b,c,d):
        print a,b,c,d


>>> tup1 = (1,2)
>>> tup2 = (3,4)
>>> foo(*chain(tup1,tup2))
1 2 3 4

Upvotes: 11

Related Questions