Python / Core Python Fundamentals Interview Questions
Can you create a tuple comprehension in Python, and what is a generator expression?
There is no tuple comprehension syntax in Python — (x for x in range(5)) is a generator expression, not a tuple. To get a tuple from a comprehension-like construct, wrap a generator expression in tuple():
# Generator expression — lazy, single-pass, no tuple
gen = (x**2 for x in range(5))
print(type(gen)) #
# Tuple from a generator expression
t = tuple(x**2 for x in range(5))
print(t) # (0, 1, 4, 9, 16)
print(type(t)) #
# List comprehension — eager, stored in memory
lst = [x**2 for x in range(5)]
# Generator expression used inline — no intermediate list
total = sum(x**2 for x in range(1_000_000)) # memory-efficient Generator expressions are the memory-friendly alternative to list comprehensions when you only need to iterate once or pass the result to a function that accepts an iterable (like sum(), max(), sorted(), list()). They are lazy — values are generated on demand.
When should you prefer a generator expression over a list comprehension?
- The sequence will be consumed once, not indexed or iterated multiple times.
- The sequence is large and you cannot afford to materialise it all in memory.
- You are passing it directly to an aggregation function (
sum,any,all).
Nested generator expressions are possible but hard to read — more than one level of nesting is usually a sign to extract a helper function.
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...
