Unpacking tuples as arguments to a function call in Python

avatar

Borislav Hadzhiev

Last updated: Jun 27, 2022

banner

Photo from Unsplash

Unpacking tuples as arguments to a function call in Python #

Use the * operator to unpack a tuple as arguments to a function call, e.g. my_func(*my_tuple_1). The * iterable unpacking operator enables us to unpack tuples in function calls and passes the items of the tuple as positional arguments to the function.

main.py
def example(a, b, c, d): return a + b + c + d my_tuple_1 = (1, 2, 3, 4) print(example(*my_tuple_1)) # 👉️ 10 my_tuple_2 = ('a', 'b', 'c', 'd') print(example(*my_tuple_2)) # 👉️ 'abcd'

We used the * iterable unpacking operator to unpack tuples as arguments to a function call.

The * iterable unpacking operator enables us to unpack an iterable in function calls, in comprehensions and in generator expressions.

You can also pass positional arguments to the function, and then unpack the tuple.

main.py
def example(a, b, c, d): return a + b + c + d my_tuple_1 = (3, 4) print(example(1, 2, *my_tuple_1)) # 👉️ 10

It is also valid syntax to expand the tuple and then pass positional arguments to the function.

main.py
def example(a, b, c, d): return a + b + c + d my_tuple_1 = (3, 4) print(example(*my_tuple_1, 1, 2)) # 👉️ 10
When we use the * operator, it passes the items of the tuple as positional arguments to the function.

You can use the operator to unpack a tuple when calling a function or when instantiating a class.

main.py
my_tuple_1 = (1, 4) # 👇️ [1, 2, 3] print(list(range(*my_tuple_1)))

The range() class expects separate start and stop arguments, so we had to unpack the tuple to create a range object.

Note that you might also see the asterisk * syntax in functions that take arbitrary number of arguments.

main.py
def example(a, b, *args): print(args) # 👉️ (3, 4) return a + b # 👉️ 3 print(example(1, 2, 3, 4))

The function takes 2 positional arguments - a and b and an arbitrary number of arguments.

The arbitrary number of arguments are wrapped up in a tuple and should be placed after any positional arguments in the function declaration.

All of the arguments we pass to the function after the first 2 positional ones are going to get wrapped up in the args tuple.

Here is an example of a function that takes an arbitrary number of arguments and unpacking a tuple in the call to the function.

main.py
def example(a, b, *args): print(args) # 👉️ (3, 4) return a + b # 👉️ 3 print(example(1, 2, *(3, 4)))

The use of the asterisk * in the call to the function unpacks the tuple and passes its items as positional arguments to the function.

Whereas, the use of the asterisk * in the function definition gathers the positional arguments after the first 2 and wraps them into a tuple.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.