[Tutor] Swapping values

Alan Gauld alan.gauld at btinternet.com
Tue Jan 5 08:28:52 EST 2016


On 05/01/16 00:37, 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?

Steven has given you a detailed answer showing how Python does it
at the low level. Conceptually there is another way to see it.

You are not actually swapping the values.
You are assigning members of a tuple. For example Python allows you
to do this:

a,b,c,d = (1,2,3,4)

And a = 1, b=2 etc.

ie Python is effectively doing the assignments:

t = (1,2,3,4)
a=t[0]
b=t[1]
etc...

Now the parens above are purely to highlight that the RHS is a tuple but
it can quite correctly be written without:

a,b,c,d = 1,2,3,4

And still a = 1, b=2 etc.
This is a fairly common idiom for initializing multiple variables.

So when in your example you write

a,b = b,a

What you are doing is just a specific case of the more general
tuple unpacking seen above, but limited to two members.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list