Member-only story
How To Use Yield in Python To Make Your Functions More Efficient
Use yield to turn your functions into memory-efficient generators
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:
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.