List Comprehensions in Python
A list comprehension is a compact way to build a list in one line. Instead of writing a loop with .append(), you describe the list directly:
# The long way
squares = []
for n in range(1, 6):
squares.append(n * n)
# The same thing as a list comprehension
squares = [n * n for n in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
Both produce the same list, but the comprehension is shorter and, once you're used to it, easier to read. Let's learn the pattern.
The basic pattern
A list comprehension has the shape:
[ expression for item in sequence ]
Read it as: "give me expression for each item in sequence".
# Double every number
nums = [1, 2, 3, 4]
doubled = [n * 2 for n in nums]
print(doubled) # [2, 4, 6, 8]
# Uppercase every word
words = ["apple", "banana"]
caps = [w.upper() for w in words]
print(caps) # ['APPLE', 'BANANA']
Adding a condition (filtering)
You can add an if at the end to keep only items that match:
[ expression for item in sequence if condition ]
nums = range(1, 11)
# Keep only even numbers
evens = [n for n in nums if n % 2 == 0]
print(evens) # [2, 4, 6, 8, 10]
# Square only the numbers greater than 5
big_squares = [n * n for n in nums if n > 5]
print(big_squares) # [36, 49, 64, 81, 100]
Transforming with if-else
If you want to transform every item (not filter), put the if/else before the for — this is a conditional expression:
nums = [1, 2, 3, 4, 5]
Want to learn this properly?
Join the waitlist for our courses — beginner-friendly, project-first classes in Jalgaon.
Browse coursesLabel each number even or odd
labels = ["even" if n % 2 == 0 else "odd" for n in nums] print(labels) # ['odd', 'even', 'odd', 'even', 'odd']
The key difference: a filtering `if` goes at the *end*; a transforming `if`/`else` goes at the *front*.
## Dictionary and set comprehensions
The same idea works for dictionaries and sets — just change the brackets:
```python
# Dictionary comprehension: number -> its square
squares = {n: n * n for n in range(1, 5)}
print(squares) # {1: 1, 2: 4, 3: 9, 4: 16}
# Set comprehension: unique word lengths
words = ["hi", "hello", "hey", "world"]
lengths = {len(w) for w in words}
print(lengths) # {2, 5, 3} — unique lengths only
A practical example
# Extract and clean a list of valid email usernames
emails = ["[email protected]", "[email protected]", "invalid-email", "[email protected]"]
# Keep only proper emails, then take the part before the @
usernames = [e.split("@")[0] for e in emails if "@" in e]
print(usernames) # ['asha', 'ravi', 'meena']
Common mistakes
- Putting the filter
ifin the wrong place: A filteringifgoes after thefor. Anif/elsethat transforms goes before thefor. Mixing these up causes syntax errors. - Making comprehensions too complex: If you nest several loops and conditions, the line becomes unreadable. At that point, a normal loop is clearer — readability wins.
- Forgetting it returns a new list: A comprehension creates a new list; it doesn't modify the original. Assign it to a variable to keep the result.
- Using
{}and expecting a list:{x for x in ...}is a set comprehension;[x for x in ...]is a list. Watch your brackets. - Side effects inside comprehensions: Don't use a comprehension just to call
print()for each item — use a plain loop. Comprehensions are for building collections.
FAQ
Are comprehensions faster than loops? Usually slightly faster, because they're optimised internally. But the main benefit is clarity for simple transformations.
Can I nest loops in a comprehension?
Yes: [x * y for x in a for y in b]. It works, but more than one nested loop quickly gets hard to read.
Is there a tuple comprehension?
Not directly — (x for x in ...) creates a generator, not a tuple. Wrap it in tuple(...) if you need a tuple.
Comprehensions build on Lists in Python and Loops in Python, so make sure those feel comfortable first. More topics on the Python learning hub.
Want to learn this properly? Join the waitlist for our Python course — taught in Jalgaon, beginner-friendly.
Want to learn this properly?
Join the waitlist for our courses — beginner-friendly, project-first classes in Jalgaon.
Browse coursesInstructor, Infoplanet
Kedar Kabra teaches Python at Infoplanet, helping beginners become confident programmers through hands-on, project-first practice.
Related guides
Dictionaries in Python
Understand Python dictionaries — storing data as key-value pairs — including adding, accessing, updating, looping, and safely reading values with .get().
Exception Handling in Python
Handle errors gracefully in Python with try, except, else, and finally — so your program responds to problems instead of crashing.
File Handling in Python
Read from and write to files in Python using with open() — covering file modes, reading line by line, appending, and safe file handling.
