Search⌘ K
AI Features

Generators

Explore how to create and use Python generators, understanding their role in efficient iteration. Learn to write generator functions with yield and manage generator state across iterations.

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 ...