Chapters
Python114 chapters

Exercises

Iterators

3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.

Exercise 1

Show that an iterator is used up: print list(it) twice.

Python
names = ["Ada", "Grace"]
it = iter(names)
# print the list twice from the iterator
Exercise 2

Write countdown as a generator so it yields 3, 2, 1.

Python
def countdown(start):
    # yield each number down to 1
    pass

print(list(countdown(3)))
Exercise 3

Make Playlist loopable more than once by returning a fresh iterator each time.

Python
class Playlist:
    def __init__(self, songs):
        self.songs = songs

p = Playlist(["a", "b"])
print(list(p))
print(list(p))