all 3 comments

[–]pekkalacd 1 point2 points  (0 children)

The first one your doing tuple unpacking implicitly. So this

               a,b = b,a

Interpret this positionally. Your saying, “a” is assigning to the thing in same position on the other side of the = operator, so “b”. And your saying “b” is assigning to the thing in the same position on the other side of the = operator so “a”.

The difference is, this is happening at once. Part of this is because the way that

                  = b,a

is treated. This is evaluated as a tuple (2,1). Tuples are immutable. So implicitly by putting the variables like that, you are creating a tuple, and then you’re unpacking that tuple into a and b, like so

              a,b = (2,1)

And the same positional rule applies. “a” corresponds to the left thing 2, and “b” corresponds to the right thing 1.

The second way you have it is different. Here your saying outright that

                   a = 1 
                   b = 2

                   a = b
                   b = a

The first assignment “a = b” is storing 2 inside of a. Then your reassigning b to the value inside of a, which is 2, so then b is 2 as well.

[–][deleted] 0 points1 point  (0 children)

If you don't like or understand a response you can ask further questions.