Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
492 views
in Technique[技术] by (71.8m points)

python - Star * operator on left vs right side of an assignment statement

This questions stems from PEP 448 -- Additional Unpacking Generalizations and is present in Python 3.5 as far as I'm aware (and not back-ported to 2.x). Specifically, in the section Disadvantages, the following is noted:

Whilst *elements, = iterable causes elements to be a list, elements = *iterable, causes elements to be a tuple. The reason for this may confuse people unfamiliar with the construct.

Which does indeed hold, for iterable = [1, 2, 3, 4], the first case yields a list:

>>> *elements, = iterable
>>> elements
[1, 2, 3, 4]

While for the second case a tuple is created:

>>> elements = *iterable,
>>> elements
(1, 2, 3, 4)

Being unfamiliar with the concept, I am confused. Can anyone explain this behavior? Does the starred expression act differently depending on the side it is on?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The difference between these two cases are explained when also taking into consideration the initial PEP for extended unpacking: PEP 3132 -- Extended iterable unpacking.

In the Abstract for that PEP we can see that:

This PEP proposes a change to iterable unpacking syntax, allowing to specify a "catch-all" name which will be assigned a list of all items not assigned to a "regular" name.

(emphasis mine)

So in the first case, after executing:

*elements, = iterable

elements is always going to be a list containing all the items in the iterable.

Even though it seems similar in both cases, the * in this case (left-side) means: catch everything that isn't assigned to a name and assign it to the starred expression. It works in a similar fashion as *args and **kwargs do in function definitions.

def spam(*args, **kwargs): 
    """ args and kwargs group positional and keywords respectively """

The second case (right-side) is somewhat different. Here we don't have the * working in a "catch everything" way as much as we have it working as it usually does in function calls. It expands the contents of the iterable it is attached to. So, the statement:

elements = *iterable, 

can be viewed as:

elements = 1, 2, 3, 4, 

which is another way for a tuple to be initialized.

Do note, a list can be created by simple using elements = [*iterable] which will unpack the contents of iterable in [] and result in an assignments of the form elements = [1, 2, 3, 4].


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...