Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Python's comma operator work during assignment?

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:

If the target is a target list enclosed in parentheses or in square brackets: The object must be an iterable with the same number of items as there are targets in the target list, and its items are assigned, from left to right, to the corresponding targets.

After reading it, I thought of writing a sample like this:

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

My assumption was that a and b both should have the value of 9.

However, I am proven wrong. 'a' has the value of 9 and 'b' has the value of 5.

Can some one help me understand this better? Why the older value of 'a' is assigned rather than the new one? As per the docs, a's value will be assigned first right? Am I missing something?

like image 769
thiruvenkadam Avatar asked Jul 16 '12 10:07

thiruvenkadam


People also ask

How does a comma operator work?

The comma operator ( , ) evaluates each of its operands (from left to right) and returns the value of the last operand. This lets you create a compound expression in which multiple expressions are evaluated, with the compound expression's final value being the value of the rightmost of its member expressions.

What does comma after variable in Python?

By adding the comma to the assignment target list, you ask Python to unpack the return value and assign it to each variable named to the left in turn. Most often, you see this being applied for functions with more than one return value: base, ext = os.path.splitext(filename)

How is comma operator useful in a for loop?

The comma operator will always yield the last value in the comma separated list. Basically it's a binary operator that evaluates the left hand value but discards it, then evaluates the right hand value and returns it. If you chain multiple of these they will eventually yield the last value in the chain.


1 Answers

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 
like image 72
Mark Byers Avatar answered Sep 19 '22 13:09

Mark Byers