What is an Iterator?
An object that produces values one at a time using __next__() and stops with StopIteration.
__iter__ vs __next__
__iter__() → returns the iterator object
__next__() → returns next value or raises StopIteration
How does a for loop work internally?
it = iter(obj)
next(it) # repeatedly until StopIteration
What is a generator?
A function that yields values one by one using yield instead of returning all at once.
What does yield do?
Returns a value, pauses the function, and resumes from the same point on next call.
Generator vs list difference?
List → stores all values in memory
Generator → produces values lazily (on demand)
Generator Expression
A compact generator using () instead of []
(x*x for x in range(5))
Why are generators useful?
Memory efficiency, handling large data, lazy evaluation.
How do you read large CSV without loading into RAM?
Use a generator to read line by line:
def read_csv(file):
with open(file) as f:
for line in f:
yield line.strip().split(‘,’)
What is the main idea behind generators?
Process data one at a time instead of all at once.