Skip to main content

Iterators and generators

An iterator is any object with __iter__ and __next__ that raises StopIteration when done; a generator function (one with yield) builds one for you. In LLD rounds use them to make custom collections (parking floors, playlists) iterable and to stream data lazily instead of building big lists.

Syntax​

def spots(n: int):
for i in range(n):
yield f"S{i}" # pauses here, resumes on next()

g = spots(3)
next(g) # -> 'S0'
list(g) # -> ['S1', 'S2'] (generator is now exhausted)

Iterator protocol by hand​

class Countdown:
def __init__(self, start: int) -> None:
self.cur = start

def __iter__(self):
return self

def __next__(self) -> int:
if self.cur <= 0:
raise StopIteration
self.cur -= 1
return self.cur + 1

print(list(Countdown(3))) # -> [3, 2, 1]

it = iter([1, 2]) # what a for loop does under the hood
next(it), next(it) # -> (1, 2)
next(it, None) # -> None (default instead of StopIteration)

Make a custom collection iterable​

class ParkingLot:
def __init__(self) -> None:
self._spots: list[str] = ["A1", "A2", "B1"]

def __iter__(self): # generator method: fresh iterator per loop
yield from self._spots

def __len__(self) -> int:
return len(self._spots)

lot = ParkingLot()
for s in lot:
print(s)
print(list(lot), list(lot)) # iterable many times, unlike a bare iterator

yield from (delegate to a sub-iterable)​

def all_spots(floors: list[list[str]]):
for floor in floors:
yield from floor # same as: for s in floor: yield s

list(all_spots([["A1", "A2"], ["B1"]])) # -> ['A1', 'A2', 'B1']

Generator expressions (lazy)​

nums = range(10)
squares = (x * x for x in nums) # O(1) memory, nothing computed yet
total = sum(x * x for x in nums) # parens can be dropped as sole arg
first_big = next((x for x in nums if x > 5), None) # -> 6

Lazy pipeline / infinite stream​

import itertools

def ticket_ids():
n = 1
while True: # infinite; only computed on demand
yield f"T{n:04d}"
n += 1

print(list(itertools.islice(ticket_ids(), 3))) # -> ['T0001', 'T0002', 'T0003']

def read_events(lines):
for line in lines:
if line.strip():
yield line.split(",")

events = read_events(["a,1", "", "b,2"]) # chain generators like Unix pipes
print(list(events)) # -> [['a', '1'], ['b', '2']]

send / return value (rare, but know it exists)​

def averager():
total = count = 0
avg = None
while True:
x = yield avg # receives value from .send()
total += x
count += 1
avg = total / count

a = averager()
next(a) # prime it
a.send(10) # -> 10.0
a.send(20) # -> 15.0

Docs​