Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 754
Codessci Avatar asked Dec 05 '22 19:12

Codessci


2 Answers

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]
like image 80
kwinkunks Avatar answered Dec 15 '22 03:12

kwinkunks


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.

like image 42
thefourtheye Avatar answered Dec 15 '22 02:12

thefourtheye