List Comprehensions
Creating lists with comprehension syntax
Interview Relevant: Pythonic code
List Comprehensions
Concise way to create lists.
Code Examples
List comprehension patterns.
python
1# Basic comprehension
2squares = [x**2 for x in range(10)]
3
4# With condition
5evens = [x for x in range(10) if x % 2 == 0]
6
7# With transformation
8upper = [s.upper() for s in ["a", "b", "c"]]
9
10# Nested comprehension
11matrix = [[i*j for j in range(3)] for i in range(3)]
12
13# Flatten nested list
14nested = [[1, 2], [3, 4]]
15flat = [x for row in nested for x in row] # [1, 2, 3, 4]
16
17# Multiple conditions
18result = [x for x in range(100) if x % 2 == 0 if x % 3 == 0]
19
20# With else (ternary in comprehension)
21result = ["even" if x % 2 == 0 else "odd" for x in range(5)]