Python List Comprehension Explained with 7 Real-Life Examples
Last Updated: July 2025
Ever seen something like [x for x in items]
in Python and thought, “Wait, what sorcery is this?”
Don’t worry — list comprehension isn’t scary. In fact, it’s one of the coolest Python tricks to write cleaner, shorter, and more readable code.
What is List Comprehension?
List comprehension is just a fancy way to build a list in one line. Instead of writing a full for loop, you can condense it into a single, readable expression.
[expression for item in iterable if condition]
Yeah, that’s the whole syntax. Simple once you see it in action.
7 Real-Life Examples
1. Convert Names to Uppercase
names = ["alice", "bob", "charlie"]
upper_names = [name.upper() for name in names]
print(upper_names)
🔹Output: ['ALICE', 'BOB', 'CHARLIE']
2. Filter Even Numbers
nums = [1, 2, 3, 4, 5, 6]
evens = [n for n in nums if n % 2 == 0]
print(evens)
🔹Output: [2, 4, 6]
3. Extract Domain Names from Emails
emails = ["alice@gmail.com", "bob@yahoo.com"]
domains = [email.split("@")[1] for email in emails]
print(domains)
🔹Output: ['gmail.com', 'yahoo.com']
4. Flatten a Nested List
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]
5. Create a List of Squares
squares = [n**2 for n in range(1, 6)]
print(squares)
🔹Output: [1, 4, 9, 16, 25]
6. Remove Punctuation from a Sentence
sentence = "Hello, world!"
clean = [ch for ch in sentence if ch.isalnum() or ch.isspace()]
print("".join(clean))
🔹Output: Hello world
7. Filter Available Products
products = {"pen": True, "pencil": False, "eraser": True}
available = [item for item, in_stock in products.items() if in_stock]
print(available)
🔹Output: ['pen', 'eraser']
When *Not* to Use List Comprehension
Just because you can, doesn’t mean you should!
If your comprehension looks like a spaghetti mess of for
and if
, consider using a regular loop for readability. Clean code > short code.
🔹Bonus: Dictionary Comprehension
You can do the same thing with dictionaries too!
original = {"a": 1, "b": 2, "c": 3}
squared = {k: v**2 for k, v in original.items()}
print(squared)
🔹Output: {'a': 1, 'b': 4, 'c': 9}
Conclusion
List comprehension might look intimidating at first, but once you practice it a few times, it becomes second nature. It's clean, powerful, and just a bit magical.
Which example was your favorite? Or got a real-life use case of your own? Let me know — and don’t forget to check out Python Lambda Functions next!