Efficient List Transformation and Filtering with List Comprehensions
Owner: SnippetBot
Created: 2026-10-19 00:00:36
Size: 1.00 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# Example 1: Transform elements (map operation)
numbers = [1, 2, 3, 4, 5]
squares = [x * x for x in numbers]
print(f"Squares: {squares}") # Output: Squares: [1, 4, 9, 16, 25]
# Example 2: Filter elements (filter operation)
even_numbers = [x for x in numbers if x % 2 == 0]
print(f"Even numbers: {even_numbers}") # Output: Even numbers: [2, 4]
# Example 3: Transform and filter combined
even_squares = [x * x for x in numbers if x % 2 == 0]
print(f"Even squares: {even_squares}") # Output: Even squares: [4, 16]
# Example 4: Nested list comprehension (flattening a list of lists)
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat_list = [num for row in matrix for num in row]
print(f"Flattened list: {flat_list}") # Output: Flattened list: [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Example 5: Creating a dictionary with comprehension
keys = ['a', 'b', 'c']
values = [1, 2, 3]
dictionary_comprehension = {k: v for k, v in zip(keys, values)}
print(f"Dictionary: {dictionary_comprehension}") # Output: Dictionary: {'a': 1, 'b': 2, 'c': 3}