python · level 3 · unit 1 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A for loop asks an for one item at a time.
Lists, strings, dictionaries and files are all : you can loop over them. Behind every for loop, Python calls iter() on the iterable to get an iterator, a little helper that remembers where it got to.
Then it calls next() on the iterator again and again, and each call hands out one item. When nothing is left, the iterator raises , and the loop stops quietly.
An iterator only goes forwards, and only once. A list can be looped over many times, because each new loop asks it for a fresh iterator.
queue = ["Ana", "Ben", "Cara"]
helper = iter(queue)
print(next(helper))
print(next(helper))
for name in helper:
print("Still waiting:", name) A file opened with with open is its own iterator, which is why reading it twice gives nothing the second time.
guess first
Two comprehensions, one iterator. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
tickets = iter([101, 102, 103])
first = [t for t in tickets]
second = [t for t in tickets]
print(first)
print(second)
your turn
Your turn. Deal the first two cards by hand.
Fill both blanks with the function that asks an iterator for its next item. list(deck) then collects whatever is left.
fix it
The average crashes with a divide by zero. Fix it!
- The error says you divided by zero. How many readings does line 3 find?
sumon line 2 used the iterator up, so nothing is left for line 3.- Make
readingsa plain list by removingiter( )on line 1, then run.
nailed it
you can see inside every for loop. :D
iter()turns an iterable into an iterator.next()hands out one item.StopIterationmeans none are left.- An iterator runs once. Keep a list if you need it twice.
new words in your collection
- iterable
- iterator
- StopIteration
This lesson isn’t saved. A free account remembers every lesson you finish.