r/pythontips • 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)
37 Upvotes

7 comments sorted by

4

u/Cybersoaker Jun 03 '16

You can also pass a tuple that will unpack into positional args:

def myFunc(a, b, c):
    print(a, b, c)

myTuple = ("Hello", "world", "!")
myFunc(*myTuple)

Python 3.5 added a bunch of new uses for tuple unpacking: https://www.python.org/dev/peps/pep-0448/

1

u/tatosaurus Jun 03 '16

coolest tip so far! haha no but really, that is quite useful.

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 a and b with a space between them, no need for a " " in the print arguments.

1

u/cismalescumlord Jun 05 '16

Thanks.

Does python have shorthand for nearly everything?

0

u/[deleted] 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.