What is a list comprehension in Python, and when should you use one?
A list comprehension builds a list in one expression: [expr for item in iterable if condition]. It is shorter and usually faster than an append loop. Use it for simple transform-and-filter work, not for complicated logic.
Explain it simply
Suppose you have a list of exam marks and want a new list of those who passed, with 5 grace marks added. In a loop you create an empty list, check each mark, and append. A comprehension writes the same plan as a single sentence: "give me mark + 5 for every mark that is at least 35".
Example
marks = [28, 45, 33, 90, 36]
passed = []
for m in marks:
if m >= 35:
passed.append(m + 5)
same = [m + 5 for m in marks if m >= 35]
print(passed) # Output: [50, 95, 41]
print(same == passed) # Output: True
squares = [n * n for n in range(1, 6)]
print(squares) # Output: [1, 4, 9, 16, 25]
pairs = [(x, y) for x in (1, 2) for y in "ab"]
print(pairs) # Output: [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]What to say in the interview
"A list comprehension creates a list from an iterable with an optional filter, in one readable expression. It avoids the repeated append calls, so it is a bit faster. If it needs more than one condition and a nested loop, or has side effects, I switch to a normal loop for readability."
Common mistakes
- Using a comprehension just to call a function for its side effect, such as
[print(x) for x in data].