Possible Duplicate:
Multiple assignment in Python
As we have learnt right since we started with C that on a computer while working in one thread, all operations occur one by one.
I have a doubt in Python 3 language. I have seen codes for swapping variable values using the expression:
a,b = b,a
Or for Fibonacci series using:
a,b = b,a+b
How can these work ? But they do work :O
Does the Python system internally create some temporary variable for these ? What’s the order of assignment so that both effectively give the correct result ?
Regards,
Nikhil
At a high level, you are creating two tuples, the left hand side and right hand side, and assigning the right one to the left, which changes the variables one by one to their opposites. Python is a higher level language, so there are more abstractions like this when compared to a language like C.
At a low level, you can see quite clearly what is happening by using the
dismodule, which can show you the python bytecode for a function:What happens is it uses
ROT_TWOto swap the order of the items on the stack, which is a very efficient way of doing this.