Skip to the content

Iterators

Python · Unit 15: Comprehensions and generators

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. 1. Predict the output

    What does this code print?

  2. 2. Complete the code

    Fill in the blank to add up the first two numbers in the list.

  3. 3. Predict the output

    What does this code print?

  4. 4. Predict the output

    What does this code print?

  5. 5. Find the bug

    This program should print the total of the points and the largest one. Which line has the error?

  6. 6. Predict the output

    What does this code print?

  7. 7. Complete the code

    Fill in the blank to catch the error for when no values are left.

  8. 8. Multiple choice

    Why can a for go through a list?

  9. 9. Predict the output

    What does this code print?

  10. 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.

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →