How does Python's comma operator works during assignment?

后端 未结 3 1193
栀梦
栀梦 2020-11-29 05:58

I was reading the assignment statements in the Python docs ( http://docs.python.org/reference/simple_stmts.html#assignment-statements ).

In that it is quoted that:

相关标签:
3条回答
  • 2020-11-29 06:14

    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
    
    0 讨论(0)
  • 2020-11-29 06:24

    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.

    0 讨论(0)
  • 2020-11-29 06:37

    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.

    0 讨论(0)
提交回复
热议问题