Python's Generator and Yield Explained

2 min read

Generators are iterators, a kind of iterable you can only iterate over once.

So what are iterators anyway?

An iterator is an object that can be iterated (looped) upon. It is used to abstract a container of data to make it behave like an iterable object. Some common iterable objects in Python are - lists, strings, dictionary.

Every generator is an iterator, but not vice versa. A generator is built by calling a function that has one or more yield expressions.

The yieldkeyword behaves like return in the sense that values that are yielded get "returned" by the generator. Unlike return, the next time the generator gets asked for a value, the generator's function, resumes where it left off after the last yield statement and continues to run until it hits another yield statement.

In simpler words, a generator is simply a function that returns a generator object on which you can call next() such that for every call it returns some value until it raises a StopIteration exception, signaling that all values have been generated.

Let's start with creating some generators

def my_generator():
    yield "First iterator object"
    yield "Second iterator object"
    yield "Third iterator object"

As per the definition, the generator function creates a generator object you can verify this.



<generator object my_generator at 0x7f0870635258>

Store this object in a variable and call the next() method on it. Every call on next() will yield a single value until all the values have been yield.

generator_object = my_generator()


First iterator object

Again from the definition, every call to next will return a value until it raises a StopIteration exception, signaling that all values have been generated so for this example we can call the next method 3 times since there are only 3 yield statements to run.

2nd Iteration



Second iterator object

3rd Iteration



Third iterator object

If you call next(generator_object) for the fourth time, you will receive StopIteration error from the Python interpreter.

Let's look at another example.

import random

def number_generator():
    while True:
        number = random.randint(0,100)
        yield number

Here the generator function will keep returning a random number since there is no exit condition from the loop.

num = number_generator()



Great, but when are generators useful?

The key advantage to generators is that the "state" of the function is preserved, unlike with regular functions where each time the stack frame is discarded, you lose all that "state". Also, generators do not store all the values in memory instead they generate the values on the fly thus making the ram more memory efficient.

Wrapping it up

Generator functions are ordinary functions defined using yield instead of return. When called, a generator function returns a generator object, which is a kind of iterator - it has a next() method. When you call next(), the next value yielded by the generator function is returned.

author's image
Abhijeet Pal Author and Editor in Chief @djangocentral

Abhijeet is a full-stack software developer from India with a strong focus on backend and system design. He is driven by the need to create impactful solutions that add value to the internet in any way possible.

LinkedIn Twitter Github

Latest Articles

Latest from djangocentral

Django 4.1 adds async-compatible interface to QuerySet

The much-awaited pull request for an async-compatible interface to Queryset just got merged into the main branch of Django.Pull Request - The Django core team has been progressively adding async suppor…
Read more →

3 min read

Making Django Admin Jazzy With django-jazzmin

Django admin is undoubtedly one of the most useful apps of Django. Over the years there has been very little change in the admin app as far as the UX is concerned and it's not a bad thing at all. Django admin was designed to provide a simple and minimali…
Read more →

4 min read