Python - tuple unpacking and generators

I came across some Python features this week that I remember blew my mind when I first learned about them. The first one is tuple unpacking, the ability to do an assignment like this:

(x0, x1) = (0, 1)

Probably not very surprising what this does but very convenient, x0 gets assigned 0 and x1 gets assigned a value of 1.  Where this starts to show its real power is doing something like this:

(x0, x1) = (x1, x0 + x1)

Here we're assigning x0 to x1 first and making x1 the sum of both, essentially building up a Fibonacci sequence. Good to note is that parentheses are optional here.

Taking this one step further, lets say we want to be able to keep walking through this Fibonacci sequence. Rather than create a list of length n and populating it, Python has a cool language feature called generators that lets your function behave as an iterator.

def fibonacci():
(x0, x1) = (0, 1)
while True:
yield x1
(x0, x1) = (x1, x0 + x1)

We're using while true in this generator because we don't want to limit how many times we can iterate. The actual magic happens using the yield keyword, it returns the current value when next() is called without exiting out of the function.

sequence = fibonacci()
print sequence.next() # 1
print sequence.next() # 1
print sequence.next() # 2

Its features like these that make Python such an interesting programming language to use for prototyping. If you haven't already, be sure to give it a try!

Posted
CategoriesPython