Practical Examples of List Comprehension
List comprehension can be used in a wide variety of scenarios to simplify and streamline your code. Let's explore some practical examples to demonstrate its versatility.
Suppose we have a list of numbers and we want to create a new list containing only the even numbers, and each number should be multiplied by 2.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
doubled_even_numbers = [x * 2 for x in numbers if x % 2 == 0]
print(doubled_even_numbers) ## Output: [4, 8, 12, 16, 20]
In this example, the list comprehension first filters the numbers to include only the even ones, and then multiplies each even number by 2 to create the new list.
Flattening Nested Lists
Suppose we have a list of lists, and we want to create a single flat list containing all the elements.
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat_list = [item for sublist in nested_list for item in sublist]
print(flat_list) ## Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
The list comprehension in this example iterates over the outer list (nested_list
) and the inner lists, and then includes each element in the resulting flat list.
Generating Sequences
Let's create a list of the first 10 square numbers.
square_numbers = [x**2 for x in range(1, 11)]
print(square_numbers) ## Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
The list comprehension generates the squares of the numbers from 1 to 10 and stores them in the square_numbers
list.
Combining Dictionaries
Suppose we have two dictionaries, and we want to create a new dictionary that combines the key-value pairs from both dictionaries.
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
combined_dict = {k: v for d in (dict1, dict2) for k, v in d.items()}
print(combined_dict) ## Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
The list comprehension in this example iterates over the two dictionaries (dict1
and dict2
), and then includes each key-value pair in the resulting combined_dict
.
These examples demonstrate the versatility of list comprehension and how it can help you write more concise and readable code. By understanding the syntax and structure of list comprehension, you can leverage this powerful feature to streamline your Python programming tasks.