Sitemap
Better Programming

Advice for programmers.

How To Use Yield in Python To Make Your Functions More Efficient

5 min readJul 19, 2021

--

Press enter or click to view image in full size
Code
Photo by Chris Ried on Unsplash.

In Python, yield is used to return from a function without destroying its variables. In a sense, yield pauses the execution of the function. When the function is invoked again, the execution continues from the last yield statement.

Using yield turns a function into a generator. Here is an illustration of functions vs. generators:

Press enter or click to view image in full size
An illustration of generator execution
Image by the author.

A generator returns a generator object, also known as an iterator, that generates one value at a time. It does not store any values. This makes a generator memory-efficient.

For example, you can use a generator to loop through a group of numbers without storing any of them in memory.

How To Turn a Function Into a Generator

To turn a function into a generator, yield a value instead of returning it. This makes the function return a generator object. This is an iterator you can loop through like a list.

Example

--

--

Responses (2)