Skip to content
LakeBench
ProblemsCommunityPricing
Sign inStart practicing
Back
  1. Home
  2. Interview prep
  3. What is an iterator?

Python · Generators & Iterators

What is an iterator?

Easypython-10
iteratoriterableprotocolnext

Question

What is an iterator in Python?

Solution

An iterable can produce an iterator (iter(obj)). An iterator is the object that walks values one at a time via next().

Protocol:

  • Iterable: defines __iter__() returning an iterator.
  • Iterator: defines __iter__() (returns self) and __next__() (returns next item or raises StopIteration).

Lists, dicts, files, and ranges are iterable. Calling iter(list) gives a separate iterator object. Generators are iterators.

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

# Custom iterator
class CountUp:
    def __init__(self, stop):
        self.current = 0
        self.stop = stop

    def __iter__(self):
        return self

    def __next__(self):
        if self.current >= self.stop:
            raise StopIteration
        value = self.current
        self.current += 1
        return value

print(list(CountUp(3)))  # [0, 1, 2]

Interview framing: "Iterable = can be looped; iterator = the cursor that yields the next item."

🎯 Put this concept into practice

Solidify this answer with real hands-on interview drills in the browser studio.

Open related drill →
PreviousNext