1. Code
  2. Python

Introduction to Python Generators

Scroll to top

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.

Basics

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.

Python Iterators

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:

1
colors= [red,blue,yellow]
2
3
def my_funct():
4
    for color in colors:
5
        print color

Behind the scenes, the for statement will call iter() on the list object. The function will then return an iterator object that defines the method __next__(), which will then access each color, one at a time. When there are no more colors left, __next__ will raise a stopIteration exception, which will in turn inform the for loop to terminate.

Iterating Over a Dictionary

1
d = {'x': 10, 'y': 20, 'z': 30}
2
for k,v in d.items():
3
    print k, v
4
5
#result

6
# y 20

7
# x 10

8
# z 30

Iterating Over Rows in a CSV File

1
import csv
2
3
with open('file.csv', newline='') as File:  
4
    reader = csv.reader(File)
5
    for row in reader:
6
        yield row

Iterating Over a String

1
my_string = 'Generators'
2
for string in my_string:
3
    print (string)
4
    
5
#result

6
7
# G

8
# e

9
# n

10
# e

11
# r

12
# a

13
# t

14
# o

15
# r

16
# s

Benefits of Using Generators

Let's discuss some of the benefits of using generators as opposed to iterators:

Easy to Implement

Building an iterator in Python will require you to implement a class with __iter__() and __next__() methods as well as taking care of any errors that may cause a stopIteration error.

1
class Reverse:
2
    """Iterator for looping over a sequence backwards."""
3
    def __init__(self, data):
4
        self.data = data
5
        self.index = len(data)
6
7
    def __iter__(self):
8
        return self
9
10
    def __next__(self):
11
        if self.index == 0:
12
            raise StopIteration
13
        self.index = self.index - 1
14
        return self.data[self.index]

As you can see above, the implementation is very lengthy. All this burden is automatically handled by generators.

Less Memory Consumption

Generators help to minimize memory consumption, especially when dealing with large data sets, because a generator will only return one item at a time.

Better Performance and Optimisation

Generators are lazy in nature. This means that they only generate values when required to do so. Unlike a normal iterator, where all values are generated regardless of whether they will be used or not, generators only generate the values needed. This will, in turn, lead to your program performing faster.

How to Create a Generator in Python

Creating a generator is very easy. All you need to do is write a normal function, but with a yield statement instead of a return statement, as shown below.

1
def gen_function():
2
    yield "python"

While a return statement terminates a function entirely, yield just pauses the function until it is called again by the next() method.

For example, the program below makes use of both the yield and next() statements.

1
def myGenerator(l):  
2
     total = 1
3
     for n in l:
4
       yield total
5
       total += n
6
     
7
newGenerator = myGenerator([10,3])
8
9
print(next(newGenerator))  
10
print(next(newGenerator))  
11
12
  

How Python Generators Work

Let's  see how generators work. Consider the example below.

1
# generator_example.py

2
3
def myGenerator(l):  
4
     total = 0
5
     for n in l:
6
       total += n
7
       yield total
8
      
9
     
10
newGenerator = myGenerator([10,20,30])
11
12
print(next(newGenerator))  
13
print(next(newGenerator))  
14
print(next(newGenerator))  
15
  

In the function above, we define a generator named myGenerator, which takes a list l as an argument. We then define a variable total and assign to it a value of zero. In addition, we loop through each element in the list and subsequently add it to the total variable.

We then instantiate newGenerator and call the next() method on it. This will run the code until it yields the first value of total, which will be 0 in this case. The function then keeps the value of the total variable until the next time the function is called. Unlike a normal return statement, which will return all the values at once, the generator will pick up from where it left off.

Below are the remaining subsequent values.

1
# generator_example.py

2
3
def myGenerator(l):  
4
     total = 0
5
     for n in l:
6
       yield total
7
       total += n
8
      
9
     
10
newGenerator = myGenerator([10,20,30])
11
12
print(next(newGenerator))  
13
print(next(newGenerator))  
14
print(next(newGenerator))  
15
  
16
# result

17
18
# 0

19
# 10

20
# 30

If you try to call the function after it has completed the loop, you will get a StopIteration error.

StopIteration is raised by the next() method to signal that there are no further items produced by the iterator.

1
0
2
10
3
30
4
5
Traceback (most recent call last):
6
  File "python", line 15, in <module>
7
StopIterationNormal function

Example 2

In this example, we show how to use multiple yield statements in a function.

1
# colors.py

2
3
def colors():
4
  yield "red"
5
  yield "blue"
6
  yield "green"
7
  
8
next_color =colors()
9
   
10
print(next(next_color))
11
print(next(next_color))
12
print(next(next_color))
13
14
# result

15
16
# red

17
# blue

18
# green

Whereas a normal function returns all the values when the function is a called, a generator waits until the next() method is called again. Once next() is called, the colors function resumes from where it had stopped.

Conclusion

Generators are more memory efficient, especially when working with very large lists or big objects. This is because you can use yields to work on smaller bits rather than having the whole data in memory all at once.

Additionally, don’t forget to see what we have available for sale and for study on Envato Market, and don't hesitate to ask any questions and provide your valuable feedback using the feed below.

Furthermore, if you feel stuck, there is a very good course on Python generators in the course section. 

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.