Iterators
Python · Unit 15: Comprehensions and generators
- Full plan
- Python
- 10 exercises
An iterator is something that knows how to hand back the next value, one at a time.
iter(items) gives you one, and next() asks it for the next value. The list doesn't change: the iterator only keeps track of where it is.
nums = [10, 20, 30]
it = iter(nums)
print(next(it))
print(next(it))Prints
10 20
The rest of the explanation is in the lesson, which is part of the full plan.
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Predict the output
What does this code print?
2. Complete the code
Fill in the blank to add up the first two numbers in the list.
3. Predict the output
What does this code print?
4. Predict the output
What does this code print?
5. Find the bug
This program should print the total of the points and the largest one. Which line has the error?
6. Predict the output
What does this code print?
7. Complete the code
Fill in the blank to catch the error for when no values are left.
8. Multiple choice
Why can a
forgo through a list?9. Predict the output
What does this code print?
10. Put the lines in order
These are the points of one game. Put the lines in order to print the first two and, separately, the ones left.
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.