Iterator

An object you can step through one item at a time with next(), until it is exhausted.

An iterator is anything you can pull values from one at a time with next(), until it runs out. Every for loop uses one under the hood: it calls next() repeatedly and stops when the iterator is exhausted.

You rarely write the iterator protocol by hand — a generator is the easiest way to make one. Lists, strings, and files are iterable: ask them for an iterator with iter() and step through it with next().

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

# A generator is already an iterator:
squares = (n * n for n in [1, 2, 3])
print(next(squares))
Output
10
20
1

Where this shows up in real Python

Iterators are anything you can loop over — files, ranges, dict views, and your own classes that define how to step through their contents.

Commonly used Iterator tools

  • iter(obj) — get an iterator from an iterable
  • next(it) — pull the next value (StopIteration at the end)
  • for x in it — the loop that uses them automatically
  • import itertools — chain, islice, count, and friends

Official documentation: Python Glossary: Iterator

Related terms