Introduction to Python Generators

, , Comments Off on Introduction to Python Generators

Generators make it easy to create iterations in Python and in return write less code. This tutorial will introduce you to Python generators, their benefits, and how they work.

A generator is a function that returns a generator object on which you can call the next() method, so that for every call it returns a value or the next value. A normal Python function uses the return keyword to return values, but generators use the keyword yield to return values. This means that any Python function containing a yield statement is a generator function.

The yield statement usually halts the function and saves the local state so that it can be resumed right where it left off. Generator functions can have one or more yield statements.

A generator is also an iterator, but what is an iterator? Before we dive into the details of generators, I think it’s important to know what iterators are because they form an integral part of this discussion.

A Python iterator is simply a class that defines an __iter__() method. Most Python objects are iterable, which means you can loop over each and every element in the objects. Examples of iterables in Python include strings, lists, tuples, dictionaries, and ranges.

Let’s consider the example below, in which we are looping over a list of colors:

Read full tutorial at code.tutsplus