1

I have just started learning python3 and I came across the following line of code :

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

How is this line a,b = b,a working? Is Python automatically creating some temp variables? And what are the unseen possibilities? I mean, can I do the same for 3 or more variables in one line?

1
  • Yes, its indeed a duplicate. Commented Jun 13, 2017 at 9:53

2 Answers 2

15

disassembling with dis:

from dis import dis

def swap(a, b):
    a, b = b, a
    return a, b

dis(swap)

gives

  7           0 LOAD_FAST                1 (b)
              3 LOAD_FAST                0 (a)
              6 ROT_TWO
              7 STORE_FAST               0 (a)
             10 STORE_FAST               1 (b)

  8          13 LOAD_FAST                0 (a)
             16 LOAD_FAST                1 (b)
             19 BUILD_TUPLE              2
             22 RETURN_VALUE

where ROT_TWO means

Swaps the two top-most stack items.

python does not need to create a temporary variable.

Sign up to request clarification or add additional context in comments.

2 Comments

This is the same as arguing that C++ swap via temp variable does not require temp variable because the temp will be stored in a register, which is essentially what happens here.
@LiranFunaro no python variable is created, though. but i kind of agree...
1

You can also do that with multiple variables but it gets tricky:

>>> a = 1
>>> b = 2
>>> c = 3
>>> a, b, c = c, a, b
>>> c
2
>>> a
3
>>> b
1
>>> 

This is useful when you want to update some values. For example, if new value of y needs to be incremented by x, and x takes the value of y:

x, y = y, y + x

2 Comments

No, Python does not create temporary variables. It is all done on the stack.
@MartijnPieters I've deleted that part, didn't realize that. Thank you :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.