Python allows a tuple (or list) of variables to appear on the left side of an assignment operation. Each variable in the tuple can receive one value (or more, if we use the
*
operator) from an iterable on the right side of the assignment. The*
is the iterable unpacking operator.
Syntax:
tuple/list of variables = any iterable object
(To create a tuple, we don’t need to use()
, this also works for iterable unpacking)
Examples:
- When we need to pack multiple values into one single variable, we use a trailing comma, because the left side of the assignment must be a tuple (or a list)
>> *a, = [1,2] >> a [1,2]
- The starred expression will be assigned a list of multiple values.
>> *a, b = 1,2,3 >> type(a) list
- We can’t use more than one starred expression in the assignment.
- We can merge the iterables using the
*
operator.
Similarly,>> a = [1,2] >> [0, *a, 3] [0, 1, 2, 3]
>> a = (i for i in range(5)) # generator is an iterable >> b = (i for i in range(5)) >> list(a) == [*b] True
- Dictionary
*
unpack keys of a dictionary>> a ={1:'a', 2:'b'} >> [0, *a, 3] # unpack keys [0, 1, 2, 3]
**
is called the dictionary unpacking operator>>letters = {"a": "A", "b": "B"} >> vowels = {"a": "a", "e": "e"} >> {**letters, **vowels} {'a': 'a', 'b': 'B', 'e': 'e', }
- Packing and Unpacking in Functions.
python函数参数
Ref1: Unpacking in Python: Beyond Parallel Assignment
Ref2: PEP 3132 – Extended Iterable Unpacking