How to Filter a List in Python Based on a Condition?

Estimated read time 2 min read

To filter a list in Python based on a condition, you can use a list comprehension or the filter() function. Here is an example code snippet that filters a list based on a condition using a list comprehension:

original_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Filter the list based on a condition using a list comprehension
new_list = [x for x in original_list if x % 2 == 0]

print(new_list)  # Output: [2, 4, 6, 8]

In this code, we define an original list (original_list) that contains integers.

Next, we create a new list (new_list) by using a list comprehension that filters the original list based on a condition. In this example, we filter the original list to only include even numbers.

Finally, we print the new list (new_list) that contains only the elements that satisfy the condition.

Alternatively, you can use the filter() function to achieve the same result. Here’s an example using filter():

original_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Filter the list based on a condition using filter()
new_list = list(filter(lambda x: x % 2 == 0, original_list))

print(new_list)  # Output: [2, 4, 6, 8]

In this code, we use the filter() function to filter the original list based on the same condition. The filter() function takes two arguments: a function that returns a Boolean value, and the iterable to be filtered. In this example, we pass a lambda function that checks if an element is even, and the original list. Finally, we convert the filtered result to a list using the list() function.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply