Filtering in a list comprehension allows you to create a new list that contains only the elements from an original list that meet certain criteria. Here's an example:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]# filter out odd numbers using a list comprehensioneven_numbers = [num for num in numbers if num % 2 == 0]print(even_numbers)# Output: [2, 4, 6, 8, 10] |
In this example, we have a list of numbers from 1 to 10. We use a list comprehension to create a new list called even_numbers that contains only the even numbers from the original list. The list comprehension consists of the following parts:
num for num in numbers: This is the basic structure of a list comprehension. It creates a new list called even_numbers and iterates over each element num in the original list numbers.if num % 2 == 0: This is a condition that filters out any elements that are not even. Only elements that satisfy the condition will be included in the new list.We can use list comprehensions to filter lists based on any condition. For example, to filter out negative numbers from a list of integers, we can use:
numbers = [1, -2, 3, -4, 5, 6, -7, 8, 9, -10]# filter out negative numbers using a list comprehensionpositive_numbers = [num for num in numbers if num >= 0]print(positive_numbers)# Output: [1, 3, 5, 6, 8, 9] |
In this example, we use a list comprehension to create a new list called positive_numbers that contains only the positive integers from the original list. The condition if num >= 0 filters out any negative integers.