Back to List

List Comprehension β€” Creating Lists in One Line

Learn how to reduce loops to one line and filter with Python's list comprehension.

Beginner
|
8min
|
Verified (2026-07)
list comprehensionlist comprehensionone-line listfilteringdict comprehension
Progress0/18 (0%)

List Comprehensions β€” Creating Lists in One Line

After completing this topic, you will:

Know the list comprehension syntax, which turns 4 lines of a for loop into 1 line, and be able to use conditional filtering and dictionary comprehensions.


The Repetitive Pattern of for Loops

When creating lists, you often write code like this:

python
numbers = [1, 2, 3, 4, 5]
squares = []
for n in numbers:
squares.append(n ** 2)
print(squares) # [1, 4, 9, 16, 25]

It's 4 lines: create an empty list, loop with a for loop, and append. This pattern repeats. Python provides a syntax to reduce this to one line:

python
squares = [n ** 2 for n in numbers]

This is a list comprehension.


Structure

python
[expression for item in iterable]

How to read it: "Create a list by taking each item from the iterable, applying the expression, and using the result."

python
# Convert strings to uppercase
names = ['alice', 'bob', 'charlie']
upper = [name.upper() for name in names]
# ['ALICE', 'BOB', 'CHARLIE']
# String length
lengths = [len(name) for name in names]
# [5, 3, 7]
# From 1 to 10
nums = [i for i in range(1, 11)]
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Conditional Filtering β€” Adding if

python
[expression for item in iterable if condition]
python
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Only even numbers
evens = [n for n in numbers if n % 2 == 0]
# [2, 4, 6, 8, 10]
# Squares of numbers greater than 3
big_squares = [n ** 2 for n in numbers if n > 3]
# [16, 25, 36, 49, 64, 81, 100]

if acts as a filter. Only items that meet the condition are included in the result.

In a for loop:

python
evens = []
for n in numbers:
if n % 2 == 0:
evens.append(n)

5 lines becomes 1 line.


if-else β€” Conditional Transformation

If you want to transform instead of filter, put if-else at the beginning:

python
# "Even" if even, "Odd" if odd
labels = ["even" if n % 2 == 0 else "odd" for n in range(1, 6)]
# ['odd', 'even', 'odd', 'even', 'odd']

The position matters:

  • Filter (exclude): [x for x in lst if condition] β€” if is at the end
  • Transformation (select): [A if condition else B for x in lst] β€” if-else is at the beginning

Dictionary Comprehension

Enclose it in curly braces to create a dictionary:

python
names = ['alice', 'bob', 'charlie']
name_len = {name: len(name) for name in names}
# {'alice': 5, 'bob': 3, 'charlie': 7}
python
# Invert values
original = {'a': 1, 'b': 2, 'c': 3}
flipped = {v: k for k, v in original.items()}
# {1: 'a', 2: 'b', 3: 'c'}

Set Comprehension

Curly braces + only the value creates a set:

python
words = ['hello', 'world', 'hello', 'python']
unique_lengths = {len(w) for w in words}
# {5, 6}

Readability Warning

python
# This is okay
result = [x * 2 for x in range(10) if x % 2 == 0]
# This is hard to read
result = [f(x, y) for x in range(10) for y in range(10) if x != y if g(x, y) > threshold]

If the comprehension can't fit in one line, or if there are nested for loops + 2 or more conditions, use a regular for loop instead. Shorter code isn't always better code. Readable code is good code.


Key Takeaway

List comprehension is the syntax [expression for item in iterable if condition] to create lists in one line. Put the filter if at the end, and the conditional transformation if-else at the beginning. {} + key: value is a dictionary, {} + only values is a set comprehension. If it doesn't fit in one line, use a for loop β€” readability comes first.

πŸ’¬ Questions & Comments

0 comments

You can post without signing in. Guest comments cannot be edited or deleted by their author.

0/2000

Loading...