Python Tip #87 (of 365):

Use tuple unpacking to swap references ๐Ÿงต

You can use tuple unpacking to swap the values of 2 variables in Python:

x, y = y, x

Outside of feeling clever in an interview, you may NEVER need to do that... but you MIGHT need to do something similar.

Here we're swapping 2 non-variable references that don't happen to be variables:

values[-2], values[-1] = values[-1], values[-2]

That swaps the last 2 items in a sequence.

๐Ÿงต (1/2)

#Python #DailyPythonTip

Or maybe you'll just reference the same variable(s) on both sides of an assignment while using tuple unpacking.

For example, here's an implementation of the Fibonacci sequence in Python:

def fibonacci():
a, b = 0, 1
while True:
a, b = b, a+b
yield a

Note that "a, b = b, a+b" assignment.

It's not quite variable swapping, but it relies on the same idea.

So while "swap 2 variables in one line" is likely pointless, the idea behind the trick does come in handy.

๐Ÿงต (2/2)