简体   繁体   中英

Extended sequence unpacking in python3

I create a list as:

>>> seq = [1, 2, 3, 4]

Now i assign the variables as follows:

>>> a, b, c, d, *e = seq
>>> print(a, b, c, d, e)

I get output as:

>>> 1 2 3 4 []

Now i change the sequence in which i assign variables as:

>>> a, b, *e, c, d = seq
>>> print(a, b, c, d, e)

I get output as:

>>> 1, 2, 3, 4, []

So my question is Why *e variable above is always assigned an empty list regardless of where it appears?

In the first case

a, b, c, d, *e = seq

since the sequence has only four elements, a , b , c and d get all of them and the rest of them will be stored in e . As nothing is left in the sequence, e is an empty list.

In the second case,

a, b, *e, c, d = seq

First two elements will be assigned to a and b respectively. But then we have two elements after the *e . So, the last two elements will be assigned to them. Now, there is nothing left in the seq . That is why it again gets an empty list.

It was a design choice, according to PEP 3132 (with my bold):

A tuple (or list) on the left side of a simple assignment (unpacking is not defined for augmented assignment) may contain at most one expression prepended with a single asterisk (which is henceforth called a "starred" expression, while the other expressions in the list are called "mandatory"). This designates a subexpression that will be assigned a list of all items from the iterable being unpacked that are not assigned to any of the mandatory expressions , or an empty list if there are no such items.

Indeed, the first example in the PEP illustrates your point:

>>> a, *b, c = range(5)
>>> a
0
>>> c
4
>>> b
[1, 2, 3]
a, b, *e, c, d = [1, 2, 3, 4]

*e says "what's left put into e ". Because you have 4 elements, empty sequence is put into e .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM