beginner
List Comprehensions
5 min read
Overview
A List Comprehension offers a concise, elegant syntax to create a new list from an existing sequence. In simple words, it replaces multi-line for loops and .append() calls with a single readable line.
Learning Objectives
- Master the syntax:
[expression for item in iterable if condition]. - Convert traditional
forloops into list comprehensions. - Use conditional logic inside list transformations.
Concept Explanation
Syntax breakdown:
python
new_list = [expression for item in iterable if condition]
- expression: The operation performed on each item (e.g.
x * 2). - item: The loop variable representing the current item.
- iterable: The source collection (list, range, tuple).
- condition (optional): A filter clause (e.g.
if x > 10).
Code Examples
Example 1 — Basic Transformation
python
numbers = [1, 2, 3, 4, 5]
# Traditional loop approach
squares_loop = []
for n in numbers:
squares_loop.append(n ** 2)
# List comprehension approach
squares_comp = [n ** 2 for n in numbers]
print("Squares:", squares_comp) # [1, 4, 9, 16, 25]
Example 2 — Filtering with Conditions
python
scores = [45, 88, 72, 90, 30, 65]
# Filter scores >= 60 and convert to passing status
passing_scores = [s for s in scores if s >= 60]
print("Passing Scores:", passing_scores) # [88, 72, 90, 65]
# If-Else transformation
status = ["Pass" if s >= 60 else "Fail" for s in scores]
print("Status:", status)
Common Mistakes
- Overcomplicating comprehensions: Writing deeply nested comprehensions with 3+ loops makes code hard to read. Use regular loops when complexity grows.
- Confusing
ifposition: Filtering condition goes at the end ([x for x in data if x > 0]), while if-else transformations go beforefor([x if x > 0 else 0 for x in data]).
Best Practices
- Keep list comprehensions short and readable.