← Back to Blog

Master Python List Comprehensions: Write Elegant Code in One Line

January 1, 2026 · 8 min read

List comprehensions are one of Python's most beloved features. They allow you to create lists in a single, readable line of code. But they're more than just syntactic sugar—they're faster, more Pythonic, and once you master them, you'll wonder how you ever lived without them.

The Problem with Traditional Loops

Let's say you want to create a list of squares from 0 to 9. The traditional approach uses a for loop:

squares = []
for i in range(10):
    squares.append(i ** 2)
print(squares)  # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

This works, but it's verbose. You need to initialize an empty list, write a loop, and append each item. There's a better way.

Enter List Comprehensions

Here's the same code using a list comprehension:

squares = [i ** 2 for i in range(10)]
print(squares)  # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

One line. Clear, concise, and Pythonic. The syntax is:

[expression for item in iterable]

Adding Conditions

Want only even squares? Add a condition:

even_squares = [i ** 2 for i in range(10) if i % 2 == 0]
print(even_squares)  # [0, 4, 16, 36, 64]

The if clause filters the items before applying the expression. The syntax becomes:

[expression for item in iterable if condition]

Real-World Examples

1. Converting Strings to Uppercase

names = ['alice', 'bob', 'charlie']
upper_names = [name.upper() for name in names]
print(upper_names)  # ['ALICE', 'BOB', 'CHARLIE']

2. Extracting Numbers from Strings

data = ['10', '20', 'invalid', '30']
numbers = [int(x) for x in data if x.isdigit()]
print(numbers)  # [10, 20, 30]

3. Flattening a Nested List

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [num for row in matrix for num in row]
print(flat)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]

This uses nested comprehensions—read it from left to right: "for each row in matrix, for each num in row, add num to the list."

Advanced Patterns

Conditional Expressions (Ternary Operator)

You can use if-else in the expression itself:

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

Dictionary Comprehensions

List comprehensions have siblings! Dictionary comprehensions work the same way:

squares_dict = {i: i ** 2 for i in range(5)}
print(squares_dict)  # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Set Comprehensions

numbers = [1, 2, 2, 3, 3, 3, 4]
unique_squares = {n ** 2 for n in numbers}
print(unique_squares)  # {1, 4, 9, 16}

Performance Benefits

List comprehensions aren't just prettier—they're faster! They're optimized at the C level in CPython, making them roughly 30% faster than equivalent for loops.

import timeit

# Traditional loop
def with_loop():
    result = []
    for i in range(1000):
        result.append(i ** 2)
    return result

# List comprehension
def with_comprehension():
    return [i ** 2 for i in range(1000)]

print(timeit.timeit(with_loop, number=10000))
print(timeit.timeit(with_comprehension, number=10000))
# Comprehension is consistently faster!

When NOT to Use List Comprehensions

While powerful, list comprehensions can be overused. Avoid them when:

  • The logic is complex: If you need multiple conditions or complex transformations, a regular loop is more readable.
  • You don't need a list: If you're just iterating once, use a generator expression instead: (i ** 2 for i in range(10))
  • Side effects are involved: List comprehensions should create lists, not perform actions like printing or writing to files.

Practice Makes Perfect

The best way to master list comprehensions is to practice. Try converting your existing for loops to comprehensions. Here are some challenges:

  1. Create a list of all vowels from a string
  2. Generate a list of tuples (number, square) for numbers 1-10
  3. Filter a list of dictionaries based on a key's value

Quick Reference

# Basic list comprehension
[expression for item in iterable]

# With condition (filter)
[expression for item in iterable if condition]

# With if-else (ternary)
[expr1 if condition else expr2 for item in iterable]

# Nested comprehension
[expression for item1 in iterable1 for item2 in iterable2]

# Dictionary comprehension
{key: value for item in iterable}

# Set comprehension
{expression for item in iterable}

# Generator expression (memory efficient)
(expression for item in iterable)

Try It in CoilPad

Try It in CoilPad

Experiment with list comprehensions locally.
See how your code works with instant feedback.

Download CoilPad