Exercises
Iterators
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
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
iter() gives an iterator, which only walks once.
names = ["Ada", "Grace"]
it = iter(names)
print(list(it))
print(list(it))Exercise 2Passed
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)))yield inside a while loop, with no class needed.
def countdown(start):
while start > 0:
yield start
start -= 1
print(list(countdown(3)))Exercise 3Passed
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))__iter__ can just hand back iter() of what it wraps.
class Playlist:
def __init__(self, songs):
self.songs = songs
def __iter__(self):
return iter(self.songs)
p = Playlist(["a", "b"])
print(list(p))
print(list(p))