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?

Naveen
  • 7,944
  • 12
  • 78
  • 165

2 Answers2

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.

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
  • 3
    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. – Liran Funaro Jun 13 '17 at 09:54
  • 2
    @LiranFunaro no *python* variable is created, though. but i kind of agree... – hiro protagonist Jun 13 '17 at 09:56
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
Gitnik
  • 564
  • 7
  • 26