Python List Comprehensions Guide with Examples
List comprehensions are a Pythonic way to create new lists from existing iterables using concise, readable, one-line syntax. They simplify code that builds lists with for loops and enable transformations, filtering, and even nesting in a few words. Let’s see how they work, why you should use them, and the most useful patterns with real code examples.
Table of Content
Why Use List Comprehensions?
- Conciseness: Write in one line what would take several with a loop.
- Readability: Express your intent more clearly (“what” not “how”).
- Performance: Often faster than equivalent
forloops in pure Python.
Syntax & Structure
[expression for item in iterable if condition]
expression: Value or operation to include in the new list.item: Variable name for each element initerable.iterable: Original list, range, or any object you loop over.if condition(optional): Only include items that meet this condition.
Basic Examples
1. Create a list of squares from 0 to 9
squares = [x**2 for x in range(10)]
print(squares)
Output
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
2. Double each value in a list
numbers = [1, 2, 3, 4]
doubled = [num * 2 for num in numbers]
print(doubled)
Output
[2, 4, 6, 8]
3. Convert a list of words to lowercase
words = ["Python", "List", "Comprehension"]
lowercased = [w.lower() for w in words]
print(lowercased)
Output
['python', 'list', 'comprehension']
Filtering with If Clauses
Add an if clause to include items only if they meet a condition.
1. Only even numbers from 0 to 9
even = [x for x in range(10) if x % 2 == 0]
print(even)
Output
[0, 2, 4, 6, 8]
2. Keep fruits that contain the letter 'a'
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
with_a = [x for x in fruits if "a" in x]
print(with_a)
Output
['apple', 'banana', 'mango']
If-Else in List Comprehension
You can use an if-else statement to assign different values based on a condition.
1. Label numbers as Even or Odd
numbers = range(1, 6)
labels = ["Even" if x % 2 == 0 else "Odd" for x in numbers]
print(labels)
Output
['Odd', 'Even', 'Odd', 'Even', 'Odd']
2. Square even, cube odd numbers
result = [x**2 if x % 2 == 0 else x**3 for x in range(1, 6)]
print(result)
Output
[1, 4, 27, 16, 125]
Nested List Comprehensions
List comprehensions can be nested to work with multiple loops or build complex structures.
1. Flatten a 2D list (matrix)
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [num for row in matrix for num in row]
print(flat)
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9]
2. Create coordinate pairs for a grid
coords = [(x, y) for x in range(3) for y in range(3)]
print(coords)
Output
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
Comparison Table: Loop vs List Comprehension
| Pattern | for Loop Version |
List Comprehension | Output |
|---|---|---|---|
| Squares of numbers (0–4) |
result = []
for x in range(5):
result.append(x*x)
|
[x*x for x in range(5)] |
[0, 1, 4, 9, 16] |
| Words with 5+ letters |
selected = []
for word in words:
if len(word) >= 5:
selected.append(word)
|
[word for word in words if len(word) >= 5] |
Words with ≥5 letters |
Useful Tips
- Keep it readable: For complex logic, a standard
forloop is sometimes clearer. - Performance: List comprehensions are often faster for simple transformations, but not always for deeply nested or side-effect code.
- Side effects: Avoid assignments or printing inside the comprehension. Stick to producing the list, not actions.
- Use generator expressions
(...)instead of[...]when you don't need the entire list in memory. - Mutability: Each run of the comprehension creates a new list; changing one list won’t affect the original.
Conclusion
List comprehensions are one of Python’s most powerful features for generating, transforming, and filtering lists in a succinct and readable way. Practice with the patterns above, and soon writing efficient, elegant one-liners will become second nature.
Comments
Post a Comment