swap values - the Python way

It's a very well known problem given to the beginners, 'swap values of two variables'. In our first introductory programming course (structured programming in C) we solved it in different ways. Most of us used another temporary variable. Some of us did some math tricks. I remember that one of my friend wrote the following code (in C):
int a, b;
scanf("%d %d", &a, &b);
printf("%d %d\n", b, a);


And it made us laugh :-D

Here is the pythonic way of doing this. Try the following code:
a = 2
b = 3
print a, b
a, b = b, a
print a, b


:-)

Comments

Unknown said…
Thanks a lot! Nicely done :)
madchuckle said…
Yes, this is one of the coolest features of Python. In fact, it uses sequence-packing-unpacking in the stack itself and is more faster than the math trick:

y = x^y
x = x^y
y = x^y

trick. The assembly code for proof can be found here. Great blog btw, as a new convert to Python, I'll follow your posts from now on.

MadChuckle Blog
Japan Shah said…
how can I swap two values from list?
Chris said…
@Japan Shah You can swap two values from a list with:

l[i],l[j]=j[j],l[i]

Popular posts from this blog

Strip HTML tags using Python

lambda magic to find prime numbers

Convert text to ASCII and ASCII to text - Python code