'python code not understand. Step by Step explanation of this code

a,b=1,2
a,b=b,a=a,b
print(a,b)
# 2 1

If someone could give me a line by line explanation of this code, help me plz



Solution 1:[1]

I thought the swap would happen like a,b=b,a. but, no swap occurs on line 2. Converting line 2 is as follows.

a, b = b, a = a, b
  1. a,b --> (1,2)
  2. a,b=(1,2)
  3. b,a=(1,2)

It's just like assigning a value to a variable.

It is equal to a=b=c=1.

a=1, b=1, c=1

Solution 2:[2]

Sure! So, line 1:

a,b = 1,2

This basically creates two variables, a and b, and assigns them values on the other side of the equal sign from left to right. So, a = 1, and b = 2.

Line 2 basically swaps everything around. As I see it, each quantity (e.g. a,b or b,a) is being made equal to something else. For example if a,b = 1,2 and you say a,b = b,a you're basically saying a,b = 2,1 so a becomes 2, and b becomes 1. When you print it, that's what you get.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 WG Ju
Solution 2 InsanityWaffles