Python / Core Python Fundamentals Interview Questions
What is list comprehension and how does it differ from a regular for loop?
List comprehension is a concise, readable way to build a new list by describing what each element should be, rather than imperatively appending in a loop. It runs faster than an equivalent for loop + append because CPython optimises the comprehension into a single opcode sequence without repeated list method lookups.
# Regular loop approach
squares = []
for x in range(1, 6):
squares.append(x ** 2)
# Equivalent list comprehension
squares = [x ** 2 for x in range(1, 6)] # [1, 4, 9, 16, 25]
# With a filter condition
even_squares = [x ** 2 for x in range(1, 11) if x % 2 == 0]
# [4, 16, 36, 64, 100]
# Nested comprehension (matrix flattening)
matrix = [[1, 2], [3, 4], [5, 6]]
flat = [num for row in matrix for num in row]
# [1, 2, 3, 4, 5, 6]The pattern is always [expression for variable in iterable if condition]. The if clause is optional. For multiple nested loops, earlier for clauses are the outer loops — same order as you would write them imperatively.
When the result is not a list but needs to be computed once, use a generator expression ((x**2 for x in range(n))) to avoid building the full list in memory. For dictionaries use dict comprehension {k: v for ...}, for sets use set comprehension {expr for ...}.
Avoid cramming complex logic into a comprehension — if you need more than one condition or a nested if/else, a regular loop is often cleaner and easier to debug.
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...
