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]Comprehension vs loop — same result.