Python List Comprehensions Explained With Real Examples
Introduction
A list comprehension is a short way to create a new list by transforming or filtering an existing one. It is not magic, and it is not always the best choice. Used well, it makes code shorter and easier to read. Used badly, it makes code hard to follow.
The basic pattern
The pattern is:
[expression for item in iterable]
For example, to square every number in a list:
numbers = [1, 2, 3, 4, 5]
squares = [n * n for n in numbers]
print(squares)
# Output: [1, 4, 9, 16, 25]
The normal loop version does the same thing in more lines:
numbers = [1, 2, 3, 4, 5]
squares = []
for n in numbers:
squares.append(n * n)
Both are correct. The comprehension is shorter when the transformation is simple.
Adding a condition
You can filter with if at the end:
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [n for n in numbers if n % 2 == 0]
print(even_numbers)
# Output: [2, 4, 6]
You can also transform strings:
names = ["ali", "sara", "omar"]
capitalised = [name.capitalize() for name in names]
print(capitalised)
# Output: ['Ali', 'Sara', 'Omar']
A practical example
Suppose you have a list of prices and you want only the prices above 100, with tax added:
prices = [50, 120, 80, 200, 90]
final_prices = [round(price * 1.10, 2) for price in prices if price > 100]
print(final_prices)
# Output: [132.0, 220.0]
Read it left to right: take each price, keep it only if it is above 100, then multiply by 1.10.
When NOT to use a list comprehension
Do not use one when:
- The logic has several nested conditions or side effects, like printing or saving to a file.
- The line becomes so long that you have to read it twice to understand it.
- You do not actually need a list, only a single result. In that case, a loop with an early exit, or a generator, may be clearer.
Readability is the test. If a beginner on your team would struggle to read it, use a normal loop. Python's own style guide values readability over cleverness.
Takeaway
Start with the simple pattern: expression, loop, optional condition. Use comprehensions for simple transforms and filters. Switch back to a loop when the logic gets complex. That balance is what makes Python code both short and readable.
Comments
Post a Comment