6

What is the difference in python between doing:

a, b = c, max(a, b)

and

a = c
b = max(a, b)

what does having the two variable assignments set on the same line do?

Alex Riley
  • 169,130
  • 45
  • 262
  • 238
farid99
  • 712
  • 2
  • 7
  • 25

2 Answers2

8

Your two snippets do different things: try with a, b and c equal to 7, 8 and 9 respectively.

The first snippet sets the three variables to 9, 8 and 9. In other words, max(a, b) is calculated before a is assigned to the value of c. Essentially, all that a, b = c, max(a, b) does is push two values onto the stack; the variables a and b are then assigned to these values when they are popped back off.

On the other hand, running the second snippet sets all three variables to 9. This is because a is set to point to the value of c before the function call max(a, b) is made.

Alex Riley
  • 169,130
  • 45
  • 262
  • 238
  • How would you rewrite the first snippet in multiple lines of code? Using a "temp" variable to hold a value I'm guessing? – farid99 Jul 23 '15 at 00:46
  • @farid99: yes a temp variable would be a good way: `temp = max(a, b)` then `a = c` then `b = temp`. Alternatively, in this case you could just carefully choose the order of the two lines, e.g. `b = max(a, b)` then `a = c` should have the same effect. – Alex Riley Jul 23 '15 at 08:14
3

They are different. The second one is like doing

a, b = c, max(c, b)

because you are assigning c to a before doing b = max(a, b). While the first one is using the old value of a to calculate it.

Assem
  • 11,574
  • 5
  • 59
  • 97