14.Comprehensions
Comprehensions in Python provide a concise and readable way to create collections such as lists, sets, and dictionaries. They allow developers to generate sequences from iterables using a single line of code, often replacing loops for clarity and efficiency.
Comprehensions are syntactic constructs that enable quick creation of new sequences by iterating over existing iterables. Python supports list, set, and dictionary comprehensions. They are widely used for filtering, transforming, and aggregating data.
1. List Comprehensions
List comprehensions provide a compact way to create lists.
The basic syntax is:
[expression for item in iterable if condition]
Example:
numbers = [1, 2, 3, 4, 5]
squares = [n**2 for n in numbers]
# Output: [1, 4, 9, 16, 25]
even_numbers = [n for n in numbers if n % 2 == 0]
# Output: [2, 4]
2. Set Comprehensions
Set comprehensions are similar to list comprehensions but create sets.
Syntax:
{expression for item in iterable if condition}
Example:
unique_squares = {n**2 for n in numbers}
# Output: {1, 4, 9, 16, 25}
3. Set Comprehensions
Dictionary comprehensions allow creating dictionaries in a single line.
Syntax:
{key_expr: value_expr for item in iterable if condition}
Example:
square_map = {n: n**2 for n in numbers}
# Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Advanced Features
Comprehensions can include conditions and nested loops. Conditional comprehensions filter elements, while nested comprehensions handle multidimensional data.
Conditional Example:
positive_numbers = [n for n in numbers if n > 0]
Nested Example:
matrix = [[1, 2], [3, 4]]
flattened = [num for row in matrix for num in row]
# Output: [1, 2, 3, 4]
Performance Considerations
Comprehensions are generally faster than equivalent loops because they are optimized internally. However, readability should not be sacrificed for brevity. Avoid overly complex comprehensions as they can reduce clarity.
Best Practices
– Use comprehensions for simple transformations and filtering.
– Prefer readability over compactness; avoid deeply nested comprehensions.
– Use generator expressions for large datasets to save memory.
Common List Methods
Method | Description |
append(x) | Add an item to the end of the list |
extend(iterable) | Extend list by appending elements from iterable |
insert(i, x) | Insert item at a given position |
remove(x) | Remove first occurrence of value |
pop([i]) | Remove and return item at position i |