[Tutor] Swapping values
Steven D'Aprano
steve at pearwood.info
Mon Jan 4 20:10:50 EST 2016
On Tue, Jan 05, 2016 at 02:37:27AM +0200, yehudak . wrote:
> In Python we can swap values between two variable a and b this way:
>
> a = 3; b = 7
> print(a, b) # =====> 3 7
>
> a, b = b, a # swapping!
> print(a, b) # =====> 7 3
>
> How does this work?
The right-hand side of the assignment is evaluated fully before the
assignment happens. Think about how you might do the same:
# right-hand side: ... = b, a
- write down b
- write down a
# left-hand side: a, b = ...
- take the first number written down (was b) and assign it to a
- take the second number written down (was a) and assign it to b
except of course Python doesn't literally "write things down".
To be technical, Python uses a stack. We can look at the byte code
generated:
py> import dis
py> code = compile("a, b = b, a", "", "single")
py> dis.dis(code)
1 0 LOAD_NAME 0 (b)
3 LOAD_NAME 1 (a)
6 ROT_TWO
7 STORE_NAME 1 (a)
10 STORE_NAME 0 (b)
13 LOAD_CONST 0 (None)
16 RETURN_VALUE
The first two commands LOAD_NAME pushes the values of b and a onto the
internal stack. ROT_TWO swaps them around, then STORE_NAME gets called
twice to assign them to a and b.
> If I split the 'magic' line into:
> a = b; b = a
> without a temp variable I get:
> print(a, b) # =====> 7 7
In this case, what you are doing is:
- let a equal the value that b has right now;
- let b equal the value that a has right now
(which is of course, the same as b)
so the second part (b = a) doesn't actually do anything. If you just
write
a = b
of course now a and b are the same.
--
Steve
More information about the Tutor
mailing list