Generators

You’ll learn about the concept of generators in Python in this lesson.

We'll cover the following...

Introduction to generators

Generators are functions that return an iterator. One kind of generator looks just like a list comprehension, except that the enclosing brackets are replaced by parentheses. Generators may be used wherever an iterator may be used, in a for loop for example.

Here’s an example. It will print e e a o.

Python 3.5
word = 'generator'
g = (c for c in word if c in 'aeiou') # similar to list comprehension
for i in g:
print(i, end=' ') # prints e e a o

Here’s how the code above works:

  • At line 2, inside the parenthesis, the for loop iterates through the word generator. Then, using an if statement, it extracts all the vowels from the word.

  • Since we are using ...