What does the yield keyword do in Python

Pratik Choudhari

The yield keyword in Python is used exclusively with generators to return values on iteration. In this article, we will explore yield in terms of its use and purpose with examples.

Purpose of yield

Generators are function like structures in Python, except on calling a generator we do not receive the output, but instead a generator object is returned. The return keyword used in a normal function is analogous to yield in a generator.

The generator returns an object only on iteration or when used with next(). When an object is yielded the state of the generator is saved in memory.

Examples of yield

Create a sequence from 0 to 9

Using a function

def create_sequence_func(): return [n for n in range(10)] print(create_sequence_func())


[1, 2, 3, 4, 5, 6, 7, 8, 9]

Using a generator

def create_sequence_gen(): for n in range(10): yield n print(create_sequence_gen())

Printing this will print only the generator object:

<generator object create_sequence_gen at 0x7fd2806d80f8>

But when iterating over a generator we can access items like with a normal sequence:

for n in create_sequence_gen(): print(n)


0 1 2 3 4 5 6 7 8 9

We could also convert a generator back to a list:



[1, 2, 3, 4, 5, 6, 7, 8, 9]

Or we can create a generator object and access items with next():

gen = create_sequence_gen() print(next(gen)) print(next(gen))


1 2

FREE VS Code / PyCharm Extensions I Use

✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link *

* This is an affiliate link. By clicking on it you will not have any additional costs, instead you will support me and my project. Thank you! 🙏

Check out my Courses