How does Python's comma operator works during assignment?

北城余情 提交于 2019-11-27 04:29:36

All the expressions to the right of the assignment operator are evaluated before any of the assignments are made.

From the Python tutorial: First steps towards programming:

The first line contains a multiple assignment: the variables a and b simultaneously get the new values 0 and 1. On the last line this is used again, demonstrating that the expressions on the right-hand side are all evaluated first before any of the assignments take place. The right-hand side expressions are evaluated from the left to the right.

Emphasis mine.

Your code is functionally equivalent to the following:

a, b = 5 + 4, 5
print a, b

Python does not have a "comma operator" as in C. Instead, the comma indicates that a tuple should be constructed. The right-hand side of

a, b = a + b, a

is a tuple with th two items a + b and a.

On the left-hand side of an assignment, the comma indicates that sequence unpacking should be performed according to the rules you quoted: a will be assigned the first element of the tuple, b the second.

You can think of the assignments happening in parallel on copies rather than sequentially and in-place.

This is why in python you dont need a swap function:

a, b = b, a

works sufficiently without requiring a temp variable, c.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!