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):
And it made us laugh :-D
Here is the pythonic way of doing this. Try the following code:
:-)
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
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
l[i],l[j]=j[j],l[i]