Using args when calling functions

suggest change

The effect of using the * operator on an argument when calling a function is that of unpacking an iterable, such as a list or a tuple:

def print_args(arg1, arg2):
    print(str(arg1) + str(arg2))

a = [1,2]
b = tuple([3,4])

print_args(*a)
# 12
print_args(*b)
# 34

Note that the length of the starred argument needs to be equal to the number of the function’s arguments when that function takes a fixed number of positional parameters, as print_args does here.

A common python idiom is to use the unpacking operator * with the zip function to reverse its effects:

a = [1,3,5,7,9]
b = [2,4,6,8,10]

zipped = zip(a,b)
# a zip iterator, not a list

zip(*zipped)
# yields (1, 3, 5, 7, 9), then (2, 4, 6, 8, 10)

In Python 3, zip returns an iterator. list(zip(*zip(a, b))) is [(1, 3, 5, 7, 9), (2, 4, 6, 8, 10)]. Consuming zipped before zip(*zipped) would leave nothing to unpack.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents