Python Tuple Unpacking
Consider the following Python code. What is the output?
>>> a, *b, c = (1, 2, 3, 4, 5)
>>> print(b)
The answer is [2, 3, 4]
.
Python uses a special syntax to pass optional arguments (*args) for tuple unpacking. This means that we can have an optional number of elements in the middle of a tuple.
We can also use the more general format where optional arguments, or varargs, appear at the end of a statement:
>>> a, b, *c = (1, 2, 3, 4, 5)
>>> print(b) # 2
>>> print(c) # [3, 4, 5]
This special syntax is more commonly used in function calls alongside the (**kwargs) syntax for keyword arguments. You can learn more about *args and **kwargs in this tutorial).
Personally, I find it helpful to remember that generally speaking arguments follow the order (args, name=args, *args, **args)
. See more in the official docs here.
Want to improve your Python? I have a list of recommended Python books.