Back to Python Mastery
AdvancedAdults
Generators and Iterators
Generators provide a way to create iterators in a simple, memory-efficient way. While a normal function computes a value and returns it, a generator function 'yields' a value and pauses its execution, ready to resume later.
This is extremely useful for working with large datasets because it doesn't require all the data to be loaded into memory at once.
A normal function to get squares:
A generator function for squares:
When you call
This prints the numbers one by one, with the function pausing and resuming at each
This is extremely useful for working with large datasets because it doesn't require all the data to be loaded into memory at once.
A normal function to get squares:
def get_squares(n):return [x**2 for x in range(n)]A generator function for squares:
def gen_squares(n):for x in range(n):yield x**2When you call
gen_squares(5), it doesn't run the code. It returns a generator object. You can then iterate over it:for i in gen_squares(5):print(i)This prints the numbers one by one, with the function pausing and resuming at each
yield. This is the core of lazy evaluation in Python.Create a Generator
Create a generator function `countdown` that yields numbers from `n` down to 1.