Python Tutorials · Python Functions

Python Generators

Learn all about Python Generators in this comprehensive tutorial.

5 min read beginner
  • Generators are functions that can pause and resume their execution.
  • The yield keyword is what makes a function a generator.
  • Generators are memory-efficient because they generate values on-the-fly instead of storing everything in memory.
  • You can manually iterate through a generator using the next() function:
  • Similar to list comprehensions, you can create generators using generator expressions with parentheses instead of square brackets:
  • Generators can be used to create the Fibonacci sequence.
  • Generators have special methods for advanced control:

Generators

Generators are functions that can pause and resume their execution.

When a generator function is called, it returns a generator object, which is an iterator.

The code inside the function is not executed yet, it is only compiled. The function only executes when you iterate over the generator.

python

The yield Keyword

The yield keyword is what makes a function a generator.

When yield is encountered, the function's state is saved, and the value is returned. The next time the generator is called, it continues from where it left off.

python
Note: Unlike return, which terminates the function, yield pauses it and can be called multiple times.

Generators Saves Memory

Generators are memory-efficient because they generate values on-the-fly instead of storing everything in memory.

For large datasets, generators save memory:

python

Using next() with Generators

You can manually iterate through a generator using the next() function:

python

When there are no more values to yield, the generator raises a StopIteration exception:

python

Generator Expressions

Similar to list comprehensions, you can create generators using generator expressions with parentheses instead of square brackets:

python
python

Fibonacci Sequence Generator

Generators can be used to create the Fibonacci sequence.

It can continue generating values indefinitely, without running out of memory:

python

Generator Methods

Generators have special methods for advanced control:

The send() method allows you to send a value to the generator:

python

The close() method stops the generator:

python

Module quiz

2 questions
1

Which of the following is true about Python Generators?

2

What is the most common pitfall when working with Python Generators?

Answer all questions to submit.