Python List Comprehensions Explained With Examples
SkillVeris Team
Engineering Team

A list comprehension builds a new list in a single readable line using the pattern [expression for item in iterable if condition].
In this guide, you'll learn:
- It replaces the common three-line pattern of creating an empty list, looping, and appending with one clear expression.
- The optional if clause filters items, so you can transform and select in the same line.
- Comprehensions are typically faster than an equivalent for loop because the work happens in optimized C-level code.
- The same syntax extends to dictionaries and sets with braces, and to memory-efficient generators with parentheses.
1What Is a List Comprehension?
A Python list comprehension is a concise way to create a new list by transforming or filtering an existing iterable, all in a single line. Its basic form is [expression for item in iterable if condition] — the expression is applied to each item, and the optional condition decides which items are included.
It exists to replace a very common pattern: creating an empty list, looping over something, and appending results one by one. A comprehension expresses that same intent more clearly and often faster, which is why experienced Python developers reach for it constantly.
2The Basic Syntax
The clearest way to understand comprehensions is to see the loop they replace side by side with the one-line version.
The Loop Version
Here is the traditional approach to building a list of squares — three lines of setup, loop, and append.
squares = []
for n in range(10):
squares.append(n * n)The Comprehension Version
The same result collapses into one expressive line that reads almost like plain English: square n for each n in the range.
squares = [n * n for n in range(10)]3Adding a Condition to Filter
The optional if clause lets you keep only the items you want, so you transform and filter in the same expression.
- evens = [n for n in range(20) if n % 2 == 0] # only even numbers
- long_words = [w for w in words if len(w) > 4] # words over 4 letters
- positives = [x for x in data if x > 0] # drop non-positive values
💡Filter Goes at the End
When the if acts as a filter, it comes after the loop. Read it as: take each item, and keep it only if the condition is true.
4Transforming and Filtering Together
The real power appears when you combine an expression that changes each item with a condition that selects items. Both happen in one pass.
For example, [n * n for n in range(20) if n % 2 == 0] squares only the even numbers. The expression on the left transforms each surviving item, while the if on the right decides which items survive. Reading left to right — expression, loop, condition — makes almost any comprehension approachable.
5Conditional Expressions in the Output
There is a second, easily confused use of if. When it appears before the for, it is not a filter — it is a conditional expression choosing what value to output.
- labels = ['even' if n % 2 == 0 else 'odd' for n in range(5)]
- clamped = [x if x < 100 else 100 for x in values] # cap at 100
- Filter form: [x for x in items if cond] # if at the end, selects items
- Value form: [a if cond else b for x in items] # if at the front, picks value
⚠️Two Different Ifs
if at the end filters items; if...else at the front chooses each output value. Mixing them up is one of the most common comprehension bugs.
6Beyond Lists: Dicts, Sets, and Generators
The comprehension syntax is not limited to lists. Swapping the brackets gives you three more powerful tools with the same familiar structure.
- Dict comprehension: {k: v for k, v in pairs} # builds a dictionary
- Set comprehension: {n % 10 for n in numbers} # unique remainders
- Generator expression: (n * n for n in range(1000000)) # lazy, memory-efficient
- Squares dict: {n: n * n for n in range(5)} # maps number to its square
🔑Generators for Big Data
Use parentheses instead of brackets when the sequence is huge. A generator produces items one at a time instead of building the whole list in memory.
7Common Mistakes to Avoid
Comprehensions are elegant until they are overused. A few habits keep them readable.
- Cramming too much logic into one line until it becomes unreadable.
- Deeply nesting comprehensions when a plain loop would be clearer.
- Confusing the filter if (at the end) with the conditional if...else (at the front).
- Using a comprehension only for side effects — a for loop is correct there.
- Building a giant list in memory when a generator would be far more efficient.
⚠️Watch Out
If a comprehension no longer fits comfortably on one line or needs a second glance to parse, rewrite it as a regular loop. Clarity beats cleverness.
8Key Takeaways
List comprehensions are a small feature with an outsized impact on clean Python.
- The pattern is [expression for item in iterable if condition].
- They replace the empty-list, loop, append pattern with one clear line.
- A trailing if filters items; a leading if...else chooses output values.
- Braces make dict and set comprehensions; parentheses make lazy generators.
- Keep them simple — if it is hard to read, use a normal loop instead.
9Frequently Asked Questions
Q: Are list comprehensions faster than for loops? A: Usually, yes. Comprehensions run their looping and appending in optimized C-level code inside the interpreter, so they are typically faster than an equivalent Python for loop that calls append repeatedly. The difference is modest for small data but adds up at scale.
Q: When should I not use a list comprehension? A: Avoid them when the logic is complex, deeply nested, or hard to read on one line, and when you only need side effects rather than a resulting list. In those cases a regular for loop is clearer and more maintainable, which matters more than saving lines.
Q: What is the difference between the two kinds of if? A: An if at the end of a comprehension filters which items are included. An if...else placed before the for is a conditional expression that chooses what value each item produces. They serve different purposes and are a frequent source of confusion.
Q: What is a generator expression? A: A generator expression uses parentheses instead of square brackets and produces items lazily, one at a time, instead of building the entire list in memory. It is ideal for very large sequences where you iterate once and do not need to store every result at the same time.
Related Reading
Get The Print Version
Download a PDF of this article for offline reading.
About the Publisher
SkillVeris Team
Engineering Team
Our engineering writers turn abstract code concepts into hands-on, project-driven learning experiences.
View all postsRelated Posts
Never miss an update
Get the latest tutorials and guides delivered to your inbox.
No spam. Unsubscribe anytime.