Simple Python Generator Pattern

Here is a simple tip for Python programming…

Ever write code that looks like this?

def foo():
    result = []
    for x in ...:
        result.append(x)
    return result

We can rewrite this code as a generator like so:

def foo():
    for x in ...:
        yield x

Although now we have to write list(foo()) if we explicitly want a list, this approach is still more flexible and efficient. Unlike the first version, we are no longer creating an entire list in memory every time. This allows us to use functions from the itertools library to generate only the amount values we need via such functions as takewhile().

For more information I suggest reading ‘Iterables vs. Iterators vs. Generators’ by Vincent Driessen, whose article is the source for this tip.

Advertisements

Add Your Thoughts

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s