How does Python's comma operator works during assignment?

thiruvenkadam picture thiruvenkadam · Jul 16, 2012 · Viewed 28.5k times · Source

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?

Answer

Mark Byers picture Mark Byers · Jul 16, 2012

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