SyntaxStudy
Sign Up
python

How to Use List Comprehensions

Write concise, readable list transformations using Python list comprehensions.

List comprehensions provide a concise way to create lists. They are generally faster and more readable than equivalent for loops.

Basic Syntax

[expression for item in iterable if condition]

When to Use

  • Transforming a list (map)
  • Filtering a list (filter)
  • Combining both in one expression

When NOT to Use

Avoid list comprehensions when the logic is complex or multi-line — use a regular for loop for readability.

Dictionary and Set Comprehensions

Same syntax works for dicts {k: v for k, v in items} and sets {x for x in items}.

Example
# Basic: square all numbers
squares = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

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

# Transform strings
words = ['hello', 'world', 'python']
upper = [w.upper() for w in words]

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

# Dictionary comprehension
scores = {'Alice': 85, 'Bob': 72, 'Carol': 91}
high = {k: v for k, v in scores.items() if v >= 80}
# {'Alice': 85, 'Carol': 91}