Excess argument capturing and parallel assignment
↳ Python
26 Oct 2020 | 4 minute read
Table of Contents
Excess positional function arguments
Excess positional arguments can be supplied to functions using *args
. As seen in the example below, we expect the arguments one
and two
, and extra arguments can be supplied using the *args
.
def arg_test(one, two, *args):
print(one)
print(two)
print(args)
arg_test(1, 2, 3, 4, 5)
1
2
(3, 4, 5)
Variable assignment
The asterisk prefix *
used for the excess positional arguments in functions can also be used for variable assignment and tuple unpacking. As seen in the example below, the variable with the asterisk prefix acts as a filler, being assigned all values not assigned to the other variables by position.
# Assign the first two values to the variables first and second.
first, second, *rest = [1, 2, 3, 4, 5]
print(first)
print(second)
print(rest)
print("----------")
# Assign the first and the last values to the variables first and last.
first, *rest, last = [1, 2, 3, 4, 5]
print(first)
print(rest)
print(last)
print("----------")
# Assign the second last and last values to the variables second_last and last.
*rest, second_last, last = [1, 2, 3, 4, 5]
print(rest)
print(second_last)
print(last)
1
2
[3, 4, 5]
----------
1
[2, 3, 4]
5
----------
[1, 2, 3]
4
5
Using the asterisk prefix one can conveniently do parallel assignment and unpacking of multiple values.