SyntaxStudy
Sign Up
Python Intermediate 9 min read

List Comprehensions

List Comprehensions

A concise way to create lists based on existing iterables.

Syntax

[expression for item in iterable if condition]

Examples

# squares of 0-9
squares = [x**2 for x in range(10)]

# even numbers
evens = [x for x in range(20) if x % 2 == 0]

# uppercase words
words = ["hello", "world"]
upper = [w.upper() for w in words]

# flattening
matrix = [[1,2],[3,4],[5,6]]
flat = [n for row in matrix for n in row]

Dict Comprehension

squares_dict = {x: x**2 for x in range(6)}
Pro Tip

Comprehensions are often faster than equivalent for-loops due to internal optimizations.