You want to swap the values of some variables, but don't want to use a temporary variable.
1 | a, b, c = b, c, a
|
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
Tags: shortcuts
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
a=5 b=6 print(a,b) a=a+b b=a-b a=a-b print(a,b)
a = a ^ b b = a ^ b a = a ^ b
Python now optimizes out the temporary tuple construction and unpacking. So go ahead and use the short form a,b = b,a. Not sure what the XOR method has going for it... less readable, less performant, and only works if the values are both the same type and __xor__ is defined for that type.