Objects and lazy iteration · Lesson 23 of 25
Iterators and generators
Produce values one at a time with yield.
8 minutes2 games
An iterable can be traversed; an iterator tracks its current position. iter() obtains an iterator and next() advances it. A function containing yield returns a generator that resumes where it paused each time a value is requested.
Python
def squares(limit):
for n in range(limit):
yield n * n
values = squares(3)
print(next(values))
print(list(values))
print(list(values))Request next
Run until yield
Yield value and pause
Resume on next request
What's the output?
values = (n * 2 for n in range(3)) print(next(values)) print(next(values))
What will this code print?
Exercise
Create a generator yielding 3, 2, 1 and print it as a list.
Expected output: [3, 2, 1]
Python
Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.