Generators in Python

Learn how generators iterate a sequence in Python.

We'll cover the following

In this lesson, you’ll learn writing iterators faster using fewer lines of code.

Simplified iterators

Previously, we implemented a basic iterator from scratch. This is what the class looks like in its simplified version:

class Counter:
  def __init__(self):
    self.n =1

  def __iter__(self):
    return self  # Returning an iterator object
 
  def __next__(self):
      if self.n <= 10:
        x = self.n
        self.n += 1
        return x  # Returning next item in the sequence
      else:
        raise StopIteration
        return

Believe it or not, that’s still a lot of code. We can lessen the length of the code by using Python’s generators.

What is a generator?

A function that is defined like a regular function, but generates the value using the yield keyword instead of return, is called a generator.

How about rewriting the above class using a generator?

def Counter():
    a = 1
    while a <= 10:
        yield a
        a += 1

See how the code’s length shrinks to five lines only!

Generator functions return a generator object. Generator objects are used either by:

  • Calling the __next__() method on the generator object
  • Using the generator object in a for-in loop

⚙️ For Python 2.x, the next() method is applicable.

Let’s implement a program to design a generator object.

Get hands-on with 1400+ tech skills courses.