Functions and flow · core
Iterators, generators and lazy pipelines
A for loop calls iter() once and next() until StopIteration. A generator is an iterator made with yield, so it is lazy and can be used only once, which lets a program handle files bigger than memory.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- An iterable has iter returning an iterator. An iterator has next (it raises StopIteration at the end) and iter returning itself.
- A for loop calls iter() once, then next() until StopIteration.
- A generator is a function with yield. Its state pauses between next() calls. It is lazy and single-pass: after one full loop it is empty.
- A generator expression is lazy and uses constant memory: sum(float(r[2]) for r in rows). A list comprehension builds the whole list; five crore floats take about 1.6 GB.
- Calling sum() twice on the same generator gives the real total, then 0. That causes a ZeroDivisionError when you compute an average. Do one pass and update total and count together.
- Reading a file line by line (for line in f) is buffered and lazy. Never use readlines() or read() on a huge file. Use csv.reader with newline="" for quoted commas.
- itertools: islice, chain, groupby (needs sorted input), batched (3.12, yields tuples). To chunk any iterable: it = iter(x); while chunk := list(islice(it, n)): yield chunk. Slicing a list does not work for generators.
- StopIteration raised inside a generator becomes RuntimeError (PEP 479). Comprehension variables do not leak out in Python 3.
The red pen
Common traps: mistake → fix
Mistake: A generator is a function that returns a list
Fix: it returns a lazy iterator that produces one item at a time.
Mistake: I can loop over a generator twice
Fix: it is exhausted after one pass.
Mistake: sum([x for x in rows]) is faster
Fix: it builds the whole list in memory first.
Mistake: A comprehension is fine for side effects like [print(x) for x in rows]
Fix: use a plain for loop.
Easy to hard
Questions interviewers ask, easy to hard
- What is the difference between an iterable, an iterator and a generator?
- What does a for loop do step by step?
- List comprehension or generator expression for five crore rows? Why?
- Why does this report average crash with ZeroDivisionError when the file has 12,000 orders?
- Write chunked(iterable, size) that works on a generator of one crore rows.
Practise
Practise with these questions
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.