List Comprehension in Python — Python Technical Interview Questions & Answers
List Comprehension in Python
List Comprehension in Python
- List comprehension builds a new list in one expression. Shape: [n * n for n in nums if n % 2 == 1]. Same result as a for-loop plus append, shorter when the idea is simple. squares = [x * x for x in range(5)] → [0, 1, 4, 9, 16]. Optional if filters items.
- Don’t nest three comprehensions. If you cannot say it in one breath, use a loop. Write the comprehension and the equivalent for-loop in the viva — same output, two styles.
- List Comprehension in Python — output: [1, 9, 25]. Odds 1,3,5 squared.
nums = [1, 2, 3, 4, 5]
│ n*n if odd
▼
[1, 9, 25]Technical Interview Tip: Comprehension vs loop — same result.
Code Examples for List Comprehension in Python
Example
# List comprehension
nums = [1, 2, 3, 4, 5]
print([n * n for n in nums if n % 2 == 1])
List Comprehension in Python — output: [1, 9, 25]. Odds 1,3,5 squared.
How to Explain List Comprehension in Python to an Interviewer
Explain List Comprehension as if you are teaching a junior — definition, then one tiny script.
[expr for x in seq if cond]. Builds a new list.
What does the example print, and why?
List Comprehension in Python — output: [1, 9, 25]
What mistake do freshers make with List Comprehension?
Over-nested comprehensions.