What Are Generators In Python?

What Are Generators In Python?

Published on October 09 2023

In this tutorial, we will learn about Python generators and their benefits in detail with an example. This tutorial is part of Python's top 25 most commonly asked interview questions.

Definition

  • Functions that return an iterable set of items ( produces a sequence of items - one at a time.)
  • It look like typical functions but their behavior is different.
  • It uses the yield statement ( one or more yield statements) instead of the return. ( to return a generator object.)
  • calling the generator function doesn’t run the function: it only creates a generator object.
  • The generator code executes when
    • the next function is applied to the generator object or
    • if the generator is iterated over (in this case, the next function is implicitly called)

Application

  • Memory Efficient: In normal function, all sequence is generated at once and stored in a memory but using a generator returns a sequence as needed by yield
  • Generate Infinite Stream
  • Easy to Implement

Example 1

squares_generator = (i * i for i in range(5))
print(squares_generator)

Output

# returns a generator object: 
<generator object <genexpr> at 0xx..

Example 2

squares_generator = (i * i for i in range(5))
print(squares_generator.__next__())
print(squares_generator.__next__())
print(squares_generator.__next__())

Output

0
1
4

Example 3

# iterate over the generator and print the values
for i in squares_generator:
    print(i)

To know about it, please refer to the official documentation website - official website.