In this lesson, you’ll learn about generators. Generators are a useful way to iterate through a sequence using constant memory. Here’s an example:
>>> g = (x for x in [1, 2, 3])
>>> g
<generator object>
>>> next(g)
1
>>> next(g)
2
>>> next(g)
3
>>> next(g)
StopIteration
You can also define generators using a function:
>>> def f():
... yield 1
... yield 2
... yield 3
>>> f()
<generator object>
>>> g = f()
>>> next(g)
1
>>> next(g)
2
>>> next(g)
3
>>> next(g)
StopIteration
If you want to learn more, check out What Are Python Generators?
James Uejio RP Team on April 27, 2020
If you want to learn more, here is a Real Python walkthrough video on generators: What Are Python Generators?