Part 2 · Section 04

Iterables and Iterators

Sequences can be iterated because you can ask them for item 0, item 1, item 2 and so on. But many collections, like sets, dictionaries, files and infinite streams of values, have no meaningful index. Python solves this with a more general idea: an object you can repeatedly ask for the next item. Every for loop, comprehension, sum(), sorted(), zip() and unpacking assignment is built on it.

The most important idea of this section, and of Part 2, is the difference between an iterable (something you can loop over, again and again) and an iterator (the single-use object that does the looping and remembers where it is). Once that distinction clicks, a whole family of puzzling bugs, like “why is my second loop empty?”, become obvious.

In this section you’ll learn:

Lectures

  1. 01Iterating Collections✓
  2. 02Iterators✓
  3. 03Iterators and Iterables✓
  4. 04Example 1 - Consuming Iterators Manually✓
  5. 05Example 2 - Cyclic Iterators✓
  6. 06Lazy Iterables✓
  7. 07Python's Built-In Iterables and Iterators✓
  8. 08Sorting Iterables✓
  9. 09The iter() Function✓
  10. 10Iterating Callables✓
  11. 11Delegating Iterators✓
  12. 12Reversed Iteration✓
  13. 13Caveat Using Iterators as Function Arguments✓

Practice: quiz & exercises

12 quiz questions · 4 coding exercises

Go to practice →