Python offers concise syntax to create lists and dictionaries using comprehensions. These are powerful tools that make your code more readable and efficient by combining loops and conditional logic into a single line.
In this blog post, we’ll explore how to use list and dictionary comprehensions with multiple examples and best practices.
1. What is Comprehension?
Comprehension is a compact way of creating sequences (like lists or dictionaries) by embedding for
loops and if
conditions inside a single expression.
2. List Comprehension
Basic Syntax:
[expression for item in iterable]
Example 1: Square of Numbers
squares = [x**2 for x in range(5)]
print(squares) # Output: [0, 1, 4, 9, 16]
Example 2: Filtering Even Numbers
evens = [x for x in range(10) if x % 2 == 0]
print(evens) # Output: [0, 2, 4, 6, 8]
Example 3: Convert Strings to Uppercase
words = ["apple", "banana", "cherry"]
upper_words = [word.upper() for word in words]
print(upper_words) # Output: ['APPLE', 'BANANA', 'CHERRY']
Example 4: Flatten a List of Lists
nested = [[1, 2], [3, 4], [5, 6]]
flat = [num for sublist in nested for num in sublist]
print(flat) # Output: [1, 2, 3, 4, 5, 6]
Example 5: Using if-else
in List Comprehension
result = ["even" if x % 2 == 0 else "odd" for x in range(5)]
print(result) # Output: ['even', 'odd', 'even', 'odd', 'even']
3. Dictionary Comprehension
Basic Syntax:
{key_expression: value_expression for item in iterable}
Example 6: Mapping Numbers to Their Squares
square_dict = {x: x**2 for x in range(5)}
print(square_dict) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Example 7: Swapping Keys and Values
original = {"a": 1, "b": 2, "c": 3}
swapped = {v: k for k, v in original.items()}
print(swapped) # Output: {1: 'a', 2: 'b', 3: 'c'}
Example 8: Filtering Items in Dictionary Comprehension
scores = {"Alice": 85, "Bob": 40, "Charlie": 90}
passed = {k: v for k, v in scores.items() if v >= 50}
print(passed) # Output: {'Alice': 85, 'Charlie': 90}
Example 9: Conditional Assignment in Dictionary
status = {k: ("Pass" if v >= 50 else "Fail") for k, v in scores.items()}
print(status) # Output: {'Alice': 'Pass', 'Bob': 'Fail', 'Charlie': 'Pass'}
Example 10: Dictionary from Two Lists
keys = ["name", "age", "city"]
values = ["Alice", 25, "New York"]
info = {k: v for k, v in zip(keys, values)}
print(info) # Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}
4. Summary Table
Type | Syntax | Use Case |
---|---|---|
List Comprehension | [expression for item in iterable] |
Create a new list from existing iterable |
Dictionary Comprehension | {key: value for item in iterable} |
Create dictionaries from other collections |
5. Best Practices
- Use comprehensions for simple operations; avoid overly complex expressions.
- Make use of conditionals to filter or transform elements.
- When readability suffers, use regular loops instead.
6. Final Thoughts
List and dictionary comprehensions are elegant and efficient features in Python that help you write cleaner and faster code. Once you get comfortable using them, they become a natural way to build and transform collections in a single readable line.