Open In App

Remove Elements From a List Based on Condition in Python

Last Updated : 09 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Python, lists are a versatile and widely used data structure. There are often situations where you need to remove elements from a list based on a specific condition. In this article, we will explore five simple and commonly used methods to achieve this task.

Remove Elements From A List Based On A Condition In Python

Below, are the methods of Remove Elements From A List Based On A Condition In Python.

Remove Elements From a List Based on Condition Using List Comprehension

In this example, the Python code, a list named `original_list` is defined with values from 1 to 9. A lambda function `condition` is then used to check if each element is even. Using list comprehension, a new list called `filtered_list` is created, excluding elements that satisfy the given condition.

Python3




original_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Example condition: remove even numbers
condition = lambda x: x % 2 == 0 
 
filtered_list = [x for x in original_list if not condition(x)]
print(filtered_list)


Output

[1, 3, 5, 7, 9]

Remove Elements From List Based On Condition Using Filter() Function

In this example, The code creates a list, `original_list`, and defines a lambda function, `condition`, to check for even numbers. Using `filter()` and a lambda expression, it generates a new list, `filtered_list`, excluding even numbers, and prints the result.

Python3




original_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Example condition: remove even numbers
condition = lambda x: x % 2 == 0 
 
filtered_list = list(filter(lambda x: not condition(x), original_list))
print(filtered_list)


Output

[1, 3, 5, 7, 9]

Remove Elements From A List Based On A Condition Using Remove() Method

In this example, the Python code , a list named original_list is created with integers from 1 to 9, and a lambda function named condition is defined to identify even numbers. The code iterates through a copy of the list using list slicing, removing elements that satisfy the condition (even numbers).

Python3




original_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
condition = lambda x: x % 2 == 0  # Example condition: remove even numbers
 
# Creating a copy of the list to avoid modifying it during iteration
for x in original_list[:]: 
    if condition(x):
        original_list.remove(x)
 
print(original_list)


Output

[1, 3, 5, 7, 9]

Conclusion

Removing elements from a list based on a condition is a common task in Python programming. The choice of method depends on the specific requirements and preferences of the programmer. The five methods discussed above – list comprehension, filter and lambda, using remove() in a loop, list comprehension with if-else, and list slicing – offer flexibility and efficiency for various use cases.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads