logo
57

Iterators

⏱️ 25 min

Iterators: Understanding What Happens Under the Hood of for

What might confuse you right now

"Why learn iterators? for just works."

Under the hood, for keeps calling next() on an iterator. Understanding this makes debugging and extending much easier.

One-line definition

An iterator is an object implementing __next__() that returns elements one by one until StopIteration.

Real-life analogy

An iterable is like a book. An iterator is the act of turning pages.

Minimal runnable example

nums = [10, 20, 30]
it = iter(nums)
print(next(it))
print(next(it))
print(next(it))

Quick quiz (5 min)

  1. Manually iterate over a string using iter() + next().
  2. Write a Counter iterator class.
  3. Add a step parameter.

Quiz answer guidelines & grading criteria

  • Answer direction: working code that covers core conditions and edge inputs from the prompt.
  • Criterion 1 (Correctness): Main flow produces correct results, key branches execute.
  • Criterion 2 (Readability): Clear variable names, no excessive nesting.
  • Criterion 3 (Robustness): Basic protection against null values, type errors, or unexpected input.

Transfer task (homework)

Implement RangeLike(start, end, step) as a custom iterator.

Acceptance criteria

You can independently:

  • Distinguish between iterable and iterator
  • Manually consume an iterator
  • Write a minimal custom iterator

Common errors & debugging steps (beginner edition)

  • Can't understand the error: read the last line for the error type (e.g., TypeError, NameError), then trace back to the relevant code line.
  • Not sure about a variable's value: temporarily add print(variable, type(variable)) at key points to verify data matches expectations.
  • Code changes aren't taking effect: confirm the file is saved, you're running the right file, and your terminal environment (venv) is correct.

Common misconceptions

  • Misconception: Iterable and iterator are the same thing.
  • Reality: An iterable produces an iterator. The iterator is what yields values one by one.