List Comprehensions
function
A concise way to create lists. More readable and often faster than equivalent for loops.
Syntax
[expression for item in iterable if condition]
Example
python
# Basic
squares = [x**2 for x in range(1, 6)]
print(squares) # [1,4,9,16,25]
# With condition
evens = [x for x in range(10) if x % 2 == 0]
print(evens) # [0,2,4,6,8]
# Nested
matrix = [[i*j for j in range(1,4)] for i in range(1,4)]
# Flatten nested list
nested = [[1,2],[3,4],[5,6]]
flat = [x for row in nested for x in row]
print(flat) # [1,2,3,4,5,6]