Python / Core Python Fundamentals Interview Questions
What is a generator in Python and how does it differ from a list?
A generator is a function that uses the yield keyword to return values one at a time, pausing execution between yields and resuming from the same point when the next value is requested. It produces an iterator without building the entire result in memory.
# List builds everything in memory first squares_list = [x**2 for x in range(1_000_000)] # ~8 MB # Generator yields one value at a time â constant memory def squares_gen(n): for x in range(n): yield x ** 2 gen = squares_gen(1_000_000) print(next(gen)) # 0 print(next(gen)) # 1 print(next(gen)) # 4 # Or use a generator expression (same thing, less code) gen2 = (x**2 for x in range(1_000_000))
Generators are lazy — they compute the next value only when asked. This makes them ideal for: large file processing (stream lines without loading the whole file), infinite sequences, data pipelines, and any situation where you do not need all results at once.
# Stream a huge log file without loading it into memory def error_lines(filepath): with open(filepath) as f: for line in f: if 'ERROR' in line: yield line.strip() for line in error_lines('/var/log/app.log'): print(line)
Once a generator is exhausted (raises StopIteration) it cannot be reset — you must create a new generator object. This is the key difference from a list, which can be iterated multiple times.
More Related questions...