Python list comprehension is one of the most powerful and elegant features in Python. If you've been writing Python for even a short time, you've likely seen a python list comprehension — a compact, readable way to create lists in a single line. Instead of writing a multi-line for loop just to build a list, python list comprehension lets you do it in one clean expression. It's faster, more Pythonic, and once you understand the python comprehension syntax, you'll find yourself using it everywhere. In this guide, we'll break down how python list comprehension works, cover conditional and nested variations, and show you when to use dict comprehension or filtering too.
Python list comprehension is a concise way to create a new list by applying an expression to each item in an iterable, all within square brackets. The basic python comprehension syntax looks like this:
[expression for item in iterable]
Think of it as a compressed version of a for loop that also returns a list. Let's look at the difference:
Traditional loop:
squares = []
for n in range(6):
squares.append(n ** 2)
Python list comprehension:
squares = [n ** 2 for n in range(6)]
Both produce [0, 1, 4, 9, 16, 25], but the python one liner list version is far more readable and concise. Python evaluates the expression (n ** 2) for every value of n in range(6) and collects the results into a new list automatically.
This is the heart of python list comprehension — you describe what you want, not how to build it step by step.
The full python comprehension syntax supports three parts:
[expression for item in iterable if condition]
Each part plays a specific role. The expression is evaluated only for items that pass the if condition. Items that fail the condition are simply skipped — they never reach the expression.
Let's see each part in action with a simple example before diving deeper.
words = ["apple", "banana", "cherry", "avocado", "blueberry"]
a_words = [w.upper() for w in words if w.startswith("a")]
print(a_words)
# Output: ['APPLE', 'AVOCADO']
Here, w.upper() is the expression, w is the loop variable, words is the iterable, and w.startswith("a") is the condition. Only words beginning with "a" pass the filter, and those get uppercased in the output.
Python conditional comprehension lets you filter which items end up in your list. The condition goes at the end of the comprehension, after the for clause.
temps = [22, 35, 18, 41, 29, 15, 38]
hot_days = [t for t in temps if t > 30]
print(hot_days)
# Output: [35, 41, 38]
Only temperatures above 30 make it into the output list. This is a classic use of python filter with comprehension — you're filtering the original list based on a rule.
You can also use an if-else directly in the expression part (not the filter part) to transform items conditionally. The syntax is slightly different here — the if-else goes before the for:
scores = [88, 45, 72, 55, 91, 63]
labels = ["pass" if s >= 60 else "fail" for s in scores]
print(labels)
# Output: ['pass', 'fail', 'pass', 'fail', 'pass', 'pass']
Every item gets a label — either "pass" or "fail" — based on the condition. Nothing is filtered out; instead, the expression itself produces different results for different inputs. This is the key difference between filtering (using if at the end) and transforming (using if-else inside the expression).
You can mix both styles in the same python list comprehension:
prices = [120, 45, 230, 80, 310, 55]
discounted = [round(p * 0.9, 2) for p in prices if p >= 100]
print(discounted)
# Output: [108.0, 207.0, 279.0]
First, prices below 100 are filtered out. Then a 10% discount is applied to the remaining prices.
The beauty of python one liner list creation is how naturally it handles common tasks. Here are patterns you'll use again and again.
employees = [
{"name": "Sara", "dept": "Engineering"},
{"name": "Tom", "dept": "Marketing"},
{"name": "Aisha", "dept": "Engineering"},
]
eng_names = [e["name"] for e in employees if e["dept"] == "Engineering"]
print(eng_names)
# Output: ['Sara', 'Aisha']
matrix = [[1, 2], [3, 4], [5, 6]]
flat = [num for row in matrix for num in row]
print(flat)
# Output: [1, 2, 3, 4, 5, 6]
sentence = "the quick brown fox"
title_words = [word.capitalize() for word in sentence.split()]
print(title_words)
# Output: ['The', 'Quick', 'Brown', 'Fox']
These python one liner list examples show how comprehension replaces loops that would otherwise take 3–5 lines each.
Python nested comprehension is when you put one comprehension inside another. This is useful for working with 2D structures like grids, matrices, or tables.
table = [[row * col for col in range(1, 5)] for row in range(1, 5)]
for row in table:
print(row)
# Output:
# [1, 2, 3, 4]
# [2, 4, 6, 8]
# [3, 6, 9, 12]
# [4, 8, 12, 16]
The outer comprehension iterates over rows, and the inner comprehension builds each row. This produces a 4×4 multiplication table as a list of lists.
original = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transposed = [[original[row][col] for row in range(3)] for col in range(3)]
print(transposed)
# Output: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
The outer loop iterates over column indices, and the inner loop pulls the value at each row for that column — effectively swapping rows and columns.
Tip: Python nested comprehension can get hard to read quickly. If you have more than two levels of nesting, consider using a regular nested loop instead for clarity.
Python filter with comprehension is arguably the most common use case. It replaces the built-in filter() function with a more readable approach.
numbers = [3, 7, 2, 9, 4, 6, 11, 8]
# Using filter()
evens_filter = list(filter(lambda x: x % 2 == 0, numbers))
# Using python filter with comprehension
evens_comp = [x for x in numbers if x % 2 == 0]
print(evens_filter) # [2, 4, 6, 8]
print(evens_comp) # [2, 4, 6, 8]
Both produce the same result, but most Python developers prefer the comprehension version because it's easier to read and doesn't require a lambda. The Python documentation actually recommends comprehensions over map() and filter() in most cases.
data = [14, 27, 33, 48, 55, 62, 71, 80]
filtered = [x for x in data if x % 2 == 0 and x > 40]
print(filtered)
# Output: [48, 62, 80]
You can chain conditions using and, or, and not just like in any Python expression.
Python comprehension isn't limited to lists. Python dict comprehension uses the same idea but produces a dictionary instead, with curly braces and a key: value expression.
fruits = ["mango", "kiwi", "grape", "papaya"]
fruit_lengths = {fruit: len(fruit) for fruit in fruits}
print(fruit_lengths)
# Output: {'mango': 5, 'kiwi': 4, 'grape': 5, 'papaya': 6}
The syntax is {key_expr: value_expr for item in iterable}. Here, each fruit name becomes a key and its length becomes the value.
original = {"a": 1, "b": 2, "c": 3}
inverted = {v: k for k, v in original.items()}
print(inverted)
# Output: {1: 'a', 2: 'b', 3: 'c'}
inventory = {"apples": 50, "bananas": 3, "cherries": 120, "dates": 8}
low_stock = {item: qty for item, qty in inventory.items() if qty < 10}
print(low_stock)
# Output: {'bananas': 3, 'dates': 8}
Python dict comprehension follows the same conditional logic as list comprehension — just with a key: value pair in the expression slot. For more on dictionaries, see the Python dict documentation.
Just like list and dict, Python also supports set comprehension using curly braces without the colon:
names = ["Alice", "Bob", "Alice", "Charlie", "Bob", "Alice"]
unique_names = {name for name in names}
print(unique_names)
# Output: {'Alice', 'Bob', 'Charlie'} (order may vary)
Set comprehension is great when you want to remove duplicates while also transforming items.
Here's a complete example that ties together python list comprehension, python conditional comprehension, python filter with comprehension, python nested comprehension, and python dict comprehension — all in a single script you can run directly.
# Python List Comprehension - Full Example
# No external libraries needed
# Sample dataset: student records
students = [
{"name": "Jordan", "score": 88, "grade": "B"},
{"name": "Priya", "score": 95, "grade": "A"},
{"name": "Marcus", "score": 52, "grade": "F"},
{"name": "Elena", "score": 74, "grade": "C"},
{"name": "Kofi", "score": 61, "grade": "D"},
{"name": "Yuki", "score": 91, "grade": "A"},
]
# 1. Python list comprehension - extract all student names
all_names = [s["name"] for s in students]
print("All students:", all_names)
# Output: All students: ['Jordan', 'Priya', 'Marcus', 'Elena', 'Kofi', 'Yuki']
# 2. Python filter with comprehension - students who passed (score >= 60)
passed = [s["name"] for s in students if s["score"] >= 60]
print("Passed:", passed)
# Output: Passed: ['Jordan', 'Priya', 'Elena', 'Kofi', 'Yuki']
# 3. Python conditional comprehension - label each student
result_labels = [
f"{s['name']}: Pass" if s["score"] >= 60 else f"{s['name']}: Fail"
for s in students
]
print("Results:", result_labels)
# Output: Results: ['Jordan: Pass', 'Priya: Pass', 'Marcus: Fail', 'Elena: Pass', 'Kofi: Pass', 'Yuki: Pass']
# 4. Python one liner list - scale scores to percentage out of 100
scaled = [round(s["score"] / 100 * 4.0, 2) for s in students] # GPA scale
print("GPA equivalents:", scaled)
# Output: GPA equivalents: [3.52, 3.8, 2.08, 2.96, 2.44, 3.64]
# 5. Python dict comprehension - name to score mapping
score_map = {s["name"]: s["score"] for s in students}
print("Score map:", score_map)
# Output: Score map: {'Jordan': 88, 'Priya': 95, 'Marcus': 52, 'Elena': 74, 'Kofi': 61, 'Yuki': 91}
# 6. Python dict comprehension with filter - only A-grade students
top_students = {s["name"]: s["score"] for s in students if s["grade"] == "A"}
print("Top students:", top_students)
# Output: Top students: {'Priya': 95, 'Yuki': 91}
# 7. Python nested comprehension - generate score brackets
brackets = [[s["name"] for s in students if low <= s["score"] < high]
for low, high in [(50, 70), (70, 90), (90, 100)]]
print("Score brackets:", brackets)
# Output: Score brackets: [['Marcus', 'Kofi'], ['Jordan', 'Elena'], ['Priya', 'Yuki']]
# 8. Set comprehension - unique grades
unique_grades = {s["grade"] for s in students}
print("Grades present:", sorted(unique_grades))
# Output: Grades present: ['A', 'B', 'C', 'D', 'F']
Output (all together):
All students: ['Jordan', 'Priya', 'Marcus', 'Elena', 'Kofi', 'Yuki']
Passed: ['Jordan', 'Priya', 'Elena', 'Kofi', 'Yuki']
Results: ['Jordan: Pass', 'Priya: Pass', 'Marcus: Fail', 'Elena: Pass', 'Kofi: Pass', 'Yuki: Pass']
GPA equivalents: [3.52, 3.8, 2.08, 2.96, 2.44, 3.64]
Score map: {'Jordan': 88, 'Priya': 95, 'Marcus': 52, 'Elena': 74, 'Kofi': 61, 'Yuki': 91}
Top students: {'Priya': 95, 'Yuki': 91}
Score brackets: [['Marcus', 'Kofi'], ['Jordan', 'Elena'], ['Priya', 'Yuki']]
Grades present: ['A', 'B', 'C', 'D', 'F']
This example uses no imports since all the features covered — python list comprehension, python dict comprehension, python nested comprehension, and python filter with comprehension — are built into Python itself. You can run this directly with any Python 3.x installation. For further reading, check the official Python tutorial on list comprehensions.
Ready to go deeper? This guide is part of a complete Python tutorial series covering everything from basics to advanced topics. Whether you're just starting out or looking to sharpen your skills, the full series has you covered. Learn the full Python tutorial here.