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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
