Fun With Unpacking

Most of us would have encountered the swapping two variables scenario in simple programmer questions.

Given,

a = 5, b = 10

There is the no-brainer, brute force approach with 1 extra variable.
c = b
b = a
a = c

Then the slightly more interesting approach using the same two variables.
a = a + b
b = b - a
a = a - b

But my recent favorite is a one-liner I recently stumbled across.

a, b = b, a

That right there is an amazing but understated feature of the Python language called “unpacking". Reading further into the concept, I realized how much the language itself uses it for other features e.g. for variable method arguments. (think *args and **kwargs)



Tags


comments powered by Disqus