📝 Python

List Comprehensions — Elegant Lists! ✨

0
Author
04e5cc8b-58ac-4bdc-bdee-661bbb
📅
Published
03.04.2026
⏱️
Reading time
10 min
👁️
Views
107
🌱
Level
Beginner

What Is a List Comprehension?

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

Without comprehension (the old way):

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

for num in numbers:
    squares.append(num ** 2)

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

With comprehension (elegant!):

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

squares = [num ** 2 for num in numbers]

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

One line instead of a loop! 🚀


Syntax

Basic:

[expression for element in iterable]

Example:

# Double every number
doubled = [x * 2 for x in [1, 2, 3, 4, 5]]
print(doubled)  # [2, 4, 6, 8, 10]

With a condition (if):

[expression for element in iterable if condition]

Example:

# Double only even numbers
doubled_even = [x * 2 for x in [1, 2, 3, 4, 5, 6] if x % 2 == 0]
print(doubled_even)  # [4, 8, 12]

With if-else:

[value_if_true if condition else value_if_false for element in iterable]

Example:

# "even" or "odd"
labels = ["even" if x % 2 == 0 else "odd" for x in [1, 2, 3, 4, 5]]
print(labels)  # ['odd', 'even', 'odd', 'even', 'odd']

Basic Examples

1. Transform every element

# Squaring
squares = [x ** 2 for x in [1, 2, 3, 4, 5]]
print(squares)  # [1, 4, 9, 16, 25]

# Multiply by 10
tens = [x * 10 for x in [1, 2, 3]]
print(tens)  # [10, 20, 30]

2. Type conversion

# Strings to numbers
strings = ["1", "2", "3", "4", "5"]
numbers = [int(s) for s in strings]
print(numbers)  # [1, 2, 3, 4, 5]

# Numbers to strings
numbers = [10, 20, 30]
strings = [str(n) for n in numbers]
print(strings)  # ['10', '20', '30']

3. Filtering with if

# Even only
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even = [x for x in numbers if x % 2 == 0]
print(even)  # [2, 4, 6, 8, 10]

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

4. Filter + transform

# Double only the even numbers
numbers = [1, 2, 3, 4, 5, 6]
doubled_even = [x * 2 for x in numbers if x % 2 == 0]
print(doubled_even)  # [4, 8, 12]

# Squares of numbers > 5
numbers = [2, 5, 7, 3, 8, 4]
big_squares = [x ** 2 for x in numbers if x > 5]
print(big_squares)  # [49, 64]

Comprehensions with Strings

String transformations

words = ["python", "javascript", "go"]

# Uppercase
upper = [word.upper() for word in words]
print(upper)  # ['PYTHON', 'JAVASCRIPT', 'GO']

# Word lengths
lengths = [len(word) for word in words]
print(lengths)  # [6, 10, 2]

# First letters
first_letters = [word[0] for word in words]
print(first_letters)  # ['p', 'j', 'g']

Working with characters

text = "Python"

# List of characters
chars = [char for char in text]
print(chars)  # ['P', 'y', 't', 'h', 'o', 'n']

# Only vowels
vowels = [char for char in text.lower() if char in 'aeiou']
print(vowels)  # ['o']

# Character codes
codes = [ord(char) for char in "ABC"]
print(codes)  # [65, 66, 67]

Filtering strings

words = ["cat", "elephant", "mouse", "lion", "kangaroo"]

# Long words (> 4 characters)
long_words = [word for word in words if len(word) > 4]
print(long_words)  # ['elephant', 'mouse', 'kangaroo']

# Words containing "a"
with_a = [word for word in words if "a" in word]
print(with_a)  # ['cat', 'elephant', 'kangaroo']

Comprehensions with Dictionaries

Extracting from dictionaries

students = [
    {"name": "Alice", "grade": 95},
    {"name": "Bob", "grade": 87},
    {"name": "Charlie", "grade": 92}
]

# Names
names = [s["name"] for s in students]
print(names)  # ['Alice', 'Bob', 'Charlie']

# Grades
grades = [s["grade"] for s in students]
print(grades)  # [95, 87, 92]

# High achievers (>= 90)
high_achievers = [s["name"] for s in students if s["grade"] >= 90]
print(high_achievers)  # ['Alice', 'Charlie']

Building dictionaries from lists

names = ["Alice", "Bob", "Charlie"]
scores = [95, 87, 92]

# Combine into dictionaries
students = [{"name": name, "score": score} for name, score in zip(names, scores)]
print(students)
# [{'name': 'Alice', 'score': 95}, {'name': 'Bob', 'score': 87}, ...]

if-else in Comprehensions

Basic if-else

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

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

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

Multiple conditions

numbers = [5, 12, 3, 18, 25, 7, 30]

# Categories: small/medium/large
categories = [
    "small" if x < 10
    else "medium" if x < 20
    else "large"
    for x in numbers
]
print(categories)
# ['small', 'medium', 'small', 'medium', 'large', 'small', 'large']

Nested Loops

Two levels of nesting

# Multiplication table
table = [x * y for x in range(1, 4) for y in range(1, 4)]
print(table)  # [1, 2, 3, 2, 4, 6, 3, 6, 9]

# Equivalent to:
for x in range(1, 4):
    for y in range(1, 4):
        table.append(x * y)

Generating pairs

# All pairs (coordinates)
pairs = [(x, y) for x in [1, 2, 3] for y in ['a', 'b']]
print(pairs)
# [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (3, 'a'), (3, 'b')]

With a condition

# Only pairs where x < y
pairs = [(x, y) for x in range(1, 6) for y in range(1, 6) if x < y]
print(pairs)
# [(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), ...]

Practical Examples

Example 1: Data Filtering

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}
]

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

Example 2: Data Transformation

# Prices with 10% tax
prices = [100, 200, 150, 300]
with_tax = [round(p * 1.1, 2) for p in prices]
print(with_tax)  # [110.0, 220.0, 165.0, 330.0]

# 20% discount on expensive items (> 150)
discounted = [p * 0.8 if p > 150 else p for p in prices]
print(discounted)  # [100, 160.0, 150, 240.0]

Example 3: Flattening a Nested List

nested = [[1, 2, 3], [4, 5], [6, 7, 8]]

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

Example 4: Data Cleaning

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

Comprehension vs map/filter

List comprehensions are an alternative to map and filter!

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

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

# List comprehension (SIMPLER!)
result = [x * 2 for x in numbers if x % 2 == 0]

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

When to use comprehension:

  • ✅ Pythonic style (recommended!)
  • ✅ More readable
  • ✅ No lambda needed
  • ✅ Complex conditions

When to use map/filter:

  • ✅ Already have a named function
  • ✅ Functional programming paradigm
  • ✅ Function composition

Dict & Set Comprehensions

Not just lists! There are comprehensions for dicts and sets too.

Dict Comprehension

# Create a dictionary
numbers = [1, 2, 3, 4, 5]
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
prices = {"apple": 50, "banana": 30, "orange": 40, "mango": 70}
expensive = {k: v for k, v in prices.items() if v > 40}
print(expensive)  # {'apple': 50, 'mango': 70}

Set Comprehension

# Set of 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!

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

Performance

Comprehensions are faster than loops!

import time

data = range(1000000)

# for loop
start = time.time()
result1 = []
for x in data:
    result1.append(x * 2)
time_for = time.time() - start

# Comprehension
start = time.time()
result2 = [x * 2 for x in data]
time_comp = time.time() - start

print(f"For loop: {time_for:.4f}s")
print(f"Comprehension: {time_comp:.4f}s")
# Comprehension is typically 20-30% faster!

Common Mistakes

Mistake 1: Wrong placement of if-else

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

# ✅ CORRECT (else BEFORE for)
result = [x * 2 if x % 2 == 0 else x for x in [1, 2, 3, 4]]
print(result)  # [1, 4, 3, 8]

Mistake 2: Overly complex logic

# ❌ BAD (unreadable!)
result = [
    x * 2 if x > 0 else abs(x) if x < -10 else 0
    for x in data
    if x % 2 == 0 or x % 3 == 0
]

# ✅ BETTER — use a regular loop when the logic is too complex
result = []
for x in data:
    if x % 2 == 0 or x % 3 == 0:
        if x > 0:
            result.append(x * 2)
        elif x < -10:
            result.append(abs(x))
        else:
            result.append(0)

Mistake 3: Thinking you’re modifying the original dict

students = [{"name": "Alice", "grade": 85}]

# ❌ DOESN'T MODIFY THE ORIGINAL!
updated = [s["grade"] + 10 for s in students]
print(students[0]["grade"])  # 85  ← unchanged!

# ✅ To modify in place:
for s in students:
    s["grade"] += 10
print(students[0]["grade"])  # 95

When NOT to Use Comprehensions

1. Side effects

# ❌ BAD (side effects in a comprehension)
[print(x) for x in [1, 2, 3]]  # Bad practice!

# ✅ GOOD (regular loop)
for x in [1, 2, 3]:
    print(x)

2. Very complex logic

# ❌ BAD (too complex)
result = [
    process(transform(validate(x)))
    for x in data
    if check1(x) and check2(x)
]

# ✅ BETTER — use a regular loop
result = []
for x in data:
    if check1(x) and check2(x):
        validated = validate(x)
        transformed = transform(validated)
        processed = process(transformed)
        result.append(processed)

3. Result is not used

# ❌ BAD
_ = [save_to_db(x) for x in data]  # We don't use the result

# ✅ GOOD
for x in data:
    save_to_db(x)

Summary

List Comprehension — what it is:

  • ✅ Build a list in one line
  • ✅ Alternative to map + filter
  • ✅ Pythonic style (recommended!)
  • ✅ Faster than a for loop
  • ✅ Readable code

Syntax:

# Basic
[expression for element in iterable]

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

# With if-else
[value_if_true if condition else value_if_false for element in iterable]

# Dict comprehension
{key: value for element in iterable}

# Set comprehension
{expression for element in iterable}

Typical usage:

# Transform
[x * 2 for x in numbers]

# Filter
[x for x in numbers if x > 0]

# Filter + transform
[x ** 2 for x in numbers if x % 2 == 0]

# Nested loops
[x * y for x in range(3) for y in range(3)]

What’s Next?

Now you know list comprehensions! 🎉

Next topics:
- Generator expressions — lazy comprehensions
- Pure functions — functions without side effects
- Pipeline — chained transformations

List comprehensions are the most Pythonic way to work with lists! 🐍✨

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

📝

Setting Up Your Environment: Python, pip, and VS …

Before writing code locally, you need to set up three tools: Python, pip, and VS...

📅 04.06.2026 👁️ 16
📝

The datetime Module: Working with Dates and Times

datetime is Python's standard module for working with dates and times. It's part of the...

📅 08.05.2026 👁️ 66
📝

.env Files and Environment Variables: Keeping Sec…

Imagine you wrote a program with an API key hardcoded in the source and pushed...

📅 08.05.2026 👁️ 75

Did you like the article?

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