You want to swap the values of some variables, but don't want to use a temporary variable.
| Python |
1 | a, b, c = b, c, a
|
Discussion
Most programming languages oblige you to use a temporary intermediate variable when swapping the values of variables:
temp = a a = b b = c c = temp
But Python lets you make use of tuple packing and unpacking to do a direct assignment:
a, b, c = b, c, a


Comments
Runtime penalty. This is great for basic coding, but for inner loops use the temporary variable.
This comes straight from the Python Tutorial, section 10.10 on Performance Measurement.
http://www.python.org/doc/2.3.3/tut/node12.html
I found tuple method is faster. don't know the reason but this is what I got on my system
0.25679183006286621
0.20631599426269531
so bye to temp variables
Sign in to comment