Search code examples
pythonswap

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

  • 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