Generators in Python

DevTechie
DevTechie
Published in
7 min readJan 16, 2024

--

Python generator is a simplified way of creating iterators. Let’s explore generators in this article.

What is Generator?

Generators in Python are used to build iterators. It aids in traversing all of the objects/items/values one by one. The generators do not produce all the items at once, rather they produce them one at a time and only when the item is required.

How to Create a Generator in Python?

In Python, we can use the below methods to create a generator function.

  1. Generator Function (Uses yield statement)
  2. Using Generator Expression

Generator Function

Generators which give a sequence of values when iterated over and which is helpful in traversing lists or tuples are created using Python’s generator functions.

Python generator functions lets you ‌define a function that behaves like a generator (in effect an iterator).

Generator function is a faster, cleaner and easier way to define a Generator. Generator is an iterable which will return an iterator.

--

--