📝 Python

List Comprehensions — Elegant Lists

P
Author
Pyland
📅
Published
03.04.2026
⏱️
Reading time
4 min
👁️
Views
182
🌿
Level
Medium

A list comprehension is a way to build a list in one line instead of a loop.

What Is a List Comprehension?

A list comprehension is a way to build a list in one line instead of a loop.

# Regular loop
squares = []
for x in [1, 2, 3, 4, 5]:
    squares.append(x ** 2)

# List comprehension — same result
squares = [x ** 2 for x in [1, 2, 3, 4, 5]]

print(squares)  # [1, 4, 9, 16, 25]

Syntax

# Basic
[expression for element in iterable]

# With filter
[expression for element in iterable if condition]

# With if-else (ternary inside the expression)
[value_if_true if condition else value_if_false for element in iterable]

All three forms in action:

numbers = [1, 2, 3, 4, 5, 6]

# Transform
doubled = [x * 2 for x in numbers]
print(doubled)  # [2, 4, 6, 8, 10, 12]

# Filter
even = [x for x in numbers if x % 2 == 0]
print(even)  # [2, 4, 6]

# Filter + transform
doubled_even = [x * 2 for x in numbers if x % 2 == 0]
print(doubled_even)  # [4, 8, 12]

# Ternary — label even/odd
labels = ["even" if x % 2 == 0 else "odd" for x in numbers]
print(labels)  # ['odd', 'even', 'odd', 'even', 'odd', 'even']

Four Core Comprehension Types

1. List Comprehension

# Type conversion
strings = ["1", "2", "3", "4"]
numbers = [int(s) for s in strings]
print(numbers)  # [1, 2, 3, 4]

# Filtering
numbers = [-5, 2, -3, 8, 0, -1, 10]
positive = [x for x in numbers if x > 0]
print(positive)  # [2, 8, 10]

# String processing
words = ["python", "javascript", "go"]
upper = [word.upper() for word in words]
print(upper)  # ['PYTHON', 'JAVASCRIPT', 'GO']

2. Dict Comprehension

numbers = [1, 2, 3, 4, 5]

# Build a dict {number: square}
squares_dict = {x: x ** 2 for x in numbers}
print(squares_dict)  # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# Swap keys and values
prices = {"apple": 50, "banana": 30, "orange": 40}
reversed_prices = {v: k for k, v in prices.items()}
print(reversed_prices)  # {50: 'apple', 30: 'banana', 40: 'orange'}

# Filter a dictionary
expensive = {k: v for k, v in prices.items() if v > 35}
print(expensive)  # {'apple': 50, 'orange': 40}

3. Set Comprehension

# Unique squares
numbers = [1, 2, 3, 2, 1, 4, 3]
squares_set = {x ** 2 for x in numbers}
print(squares_set)  # {1, 4, 9, 16}  ← duplicates removed automatically

# Unique long words
words = ["python", "go", "java", "python", "go"]
long_unique = {w for w in words if len(w) > 3}
print(long_unique)  # {'java', 'python'}

4. Conditional Comprehensions (if-else)

numbers = [-5, 3, -2, 8, -1, 10]

# Replace negatives with 0
non_negative = [x if x >= 0 else 0 for x in numbers]
print(non_negative)  # [0, 3, 0, 8, 0, 10]

# Multiple conditions — size categories
data = [5, 12, 3, 18, 25, 7, 30]
categories = [
    "small" if x < 10
    else "medium" if x < 20
    else "large"
    for x in data
]
print(categories)
# ['small', 'medium', 'small', 'medium', 'large', 'small', 'large']

Comprehension vs map/filter

List comprehensions are a readable alternative to map() + filter().

numbers = [1, 2, 3, 4, 5, 6]

# map + filter — less readable, requires lambda
result = list(map(lambda x: x * 2, filter(lambda x: x % 2 == 0, numbers)))

# List comprehension — simpler and clearer
result = [x * 2 for x in numbers if x % 2 == 0]

print(result)  # [4, 8, 12]

Use map/filter when you already have a named function or need functional-style composition:

import math

numbers = [1, 4, 9, 16, 25]

# map with a named function — concise
roots = list(map(math.sqrt, numbers))
print(roots)  # [1.0, 2.0, 3.0, 4.0, 5.0]

Practical Example: Processing a Product Catalog

data = [
    {"name": "Phone", "price": 500, "in_stock": True},
    {"name": "Laptop", "price": 1200, "in_stock": False},
    {"name": "Mouse", "price": 25, "in_stock": True},
    {"name": "Monitor", "price": 300, "in_stock": True},
]

# Items in stock and affordable (< 600)
available = [
    p["name"]
    for p in data
    if p["in_stock"] and p["price"] < 600
]
print(available)  # ['Phone', 'Mouse', 'Monitor']

# Prices with 10% tax for in-stock items
prices_with_tax = {
    p["name"]: round(p["price"] * 1.1, 2)
    for p in data
    if p["in_stock"]
}
print(prices_with_tax)
# {'Phone': 550.0, 'Mouse': 27.5, 'Monitor': 330.0}

# Flatten a nested list
nested = [[1, 2, 3], [4, 5], [6, 7, 8]]
flat = [item for sublist in nested for item in sublist]
print(flat)  # [1, 2, 3, 4, 5, 6, 7, 8]

# Clean data: strip whitespace and drop empty strings
lines = ["  Python  ", "", "  Go", "   ", "Java  "]
clean = [line.strip() for line in lines if line.strip()]
print(clean)  # ['Python', 'Go', 'Java']

Common Mistake: Wrong Position of if-else

# ❌ SYNTAX ERROR: else placed after for
result = [x * 2 for x in [1, 2, 3, 4] if x % 2 == 0 else x]
# SyntaxError!

# ✅ CORRECT: if-else BEFORE for (it is a ternary expression)
result = [x * 2 if x % 2 == 0 else x for x in [1, 2, 3, 4]]
print(result)  # [1, 4, 3, 8]

The rule: if without else is a filter — it goes after for. if ... else ... is a ternary expression — it goes before for.

Your reaction to the article

💬 Comments (0)

🔐 Sign in to leave a comment
🚪 Login
💭

No comments yet

Be the first to share your opinion about this article!

🔗 Similar

Similar articles

Continue learning with these materials

📝

Event Loop in Python: How asyncio Achieves "Paral…

Event loop is the heart of asyncio. It doesn't run code in parallel across multiple...

📅 30.06.2026 👁️ 135
📝

pytest-django: Testing Django

Охватываемые темы: Installation, @pytest.mark.djangodb, Fixtures, Testing views.

📅 30.06.2026 👁️ 143
📝

pip: Python Package Manager

Охватываемые темы: Installing packages, Upgrading and removing, requirements.txt, Virtual environment.

📅 30.06.2026 👁️ 139

Did you like the article?

Subscribe to our updates and receive new articles first. Grow with PyLand!