0

So, I don't understand why x,y = y,x = 1,2 results in x,y = 2,1. As far as my understanding of Python goes, I would have assumed that the sentence is evaluated from the right. In effect, I expected x,y = y,x = 1,2 to be equivalent to:

y,x = 1,2
x,y = y,x

However, when I actually run this in Python I get x,y = 1,2.

Additionally, when I extend the statement I can understand how the logic extends.

>>> x,y = 1,2
>>> print(x,y)
1 2
>>> x,y = y,x = 1,2
>>> print(x,y)
2 1
>>> x,y = y,x = x,y = 1,2
>>> print(x,y)
1 2
>>> x,y = y,x = x,y = y,x = 1,2
>>> print(x,y)
2 1
>>> x,y = y,x = x,y = y,x = x,y = 1,2
>>> print(x,y)
1 2

That x,y switches between 1,2 and 2,1 depending on whether I have an even or odd number of flips makes sense to me. However, why does the below not evaluate similarly?

>>> x,y = 1,2
>>> print(x,y)
1 2
>>> x,y = 1,2
>>> x,y = y,x
>>> print(x,y)
2 1
>>> x,y = 1,2
>>> x,y = y,x = x,y
>>> print(x,y)
2 1
>>> x,y = 1,2
>>> x,y = y,x = x,y = y,x
>>> print(x,y)
2 1
>>> x,y = 1,2
>>> x,y = y,x = x,y = y,x = x,y
>>> print(x,y)
2 1

Note: The above was evaluated in Python 3.10.0

Summarily, there are two things I don't understand and would like to help with on understanding:

  1. Why does x,y = y,x = 1,2 result in x,y = 2,1?
  2. Why do the code in the third code block evaluate as they do?

Thank you!

LunarFox
  • 9
  • 2
  • 1
    ...it does, actually, and it answers both of them. I'm somewhat embarrassed that I couldn't find that post before. I think a keyword that i missed in my searches was 'chained'. Thank you so much! – LunarFox Feb 15 '23 at 10:01

0 Answers0