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:
- Why does
x,y = y,x = 1,2
result in x,y = 2,1? - Why do the code in the third code block evaluate as they do?
Thank you!