r/pythontips • u/CrayonConstantinople Mod • Jun 02 '16
Syntax Swapping variables using unpacking
Swap two variables without needing to create a temporary variable
a, b = 1, 2
a, b = b, a
a, b #(2, 1)3
1
1
u/cismalescumlord Jun 03 '16
This is reminiscent of the old XOR algorithm for swapping variables
a = 1
b = 2
print(a, " ", b)
a = a ^ b
b = b ^ a
a = a ^ b
print(a, " ", b)Purely for historical and geeky interest.
2
u/donnieod Jun 05 '16
print(a, b)will print the values of
aandbwith a space between them, no need for a" "in the print arguments.1
0
Jun 03 '16
[deleted]
1
u/TeamSpen210 Jun 03 '16
Specifically, 2- and 3-long tuples not produce tuples. The optimisation does still maintain the correct operation order, however - the right side is evaluated, and then all values are assigned from left to right.
4
u/Cybersoaker Jun 03 '16
You can also pass a tuple that will unpack into positional args:
Python 3.5 added a bunch of new uses for tuple unpacking: https://www.python.org/dev/peps/pep-0448/