- Published on
10. List comprehensions in Python
- Authors
10. What are list comprehensions and why do we use them, if at all?
✅ What Are List Comprehensions in Python?
A list comprehension is a concise, readable way to create a new list by applying an expression to each item in an iterable (like a list, range, etc.), optionally filtering with a condition.
🧱 Basic Syntax:
[expression for item in iterable if condition]
🧠 Why Use Them?
- More concise than
for
loops. - More readable for simple operations.
- Faster than equivalent loops in many cases.
🔁 Example vs. Traditional Loop:
✅ List comprehension:
squares = [x**2 for x in range(10)]
❌ Equivalent with loop:
squares = []
for x in range(10):
squares.append(x**2)
🎯 With Condition:
even_squares = [x**2 for x in range(10) if x % 2 == 0]
🧱 Nested List Comprehension:
matrix = [[i * j for j in range(3)] for i in range(3)]
# Output: [[0, 0, 0], [0, 1, 2], [0, 2, 4]]
⚠️ When Not to Use:
- When the logic is too complex — use a regular loop for clarity.
- When you need to perform multiple actions in the loop body.
Summary:
Feature | Benefit |
---|---|
Compact syntax | Less code for simple list creation |
Readability | Clearer for simple expressions |
Performance | Often faster than loops |