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.
More Related questions...