This tutorial will discuss multiple ways to remove elements from a list in Python based on a certain condition.
Table Of Contents
Technique 1: Using List Comprehension & Lambda Function
Suppose we have a list of numbers and we want to remove certain elements based on a condition.
sampleList = [45, 67, 22, 45, 22, 89, 71, 22, 51]
For instance, let’s say we want to remove all even numbers from the list. To achieve this, we’ve crafted a condition using a lambda function.
We will iterate over each element in the list using list comprehension, and skip the elements for which the lambda function returns True. Essentially, we will filter each element through this lambda function, and if it returns True, we will include it. Consequently, all even numbers will be omitted. By assigning this filtered list back to the original list variable, we create the impression that all even numbers have been excised. In essence, we’ve culled elements from the list based on a specific condition.
Let’s see the complete example,
# A List of Numbers sampleList = [45, 67, 22, 45, 22, 89, 71, 22, 51] print("Original List:", sampleList) # Lambda Function, acts like a Condition Function # returns true if given number is odd only condition = lambda x: x % 2 != 0 # Removing all even numbers using list comprehension sampleList = [item for item in sampleList if condition(item)] print("List after removing even numbers:") print(sampleList)
Output
Frequently Asked:
Original List: [45, 67, 22, 45, 22, 89, 71, 22, 51] List after removing even numbers: [45, 67, 45, 89, 71, 51]
Technique 2: Using filter() method
Alternatively, the filter() function can also be used to remove elements based on a condition. With the filter() function, the condition (often a function) is passed as the first argument, and the list is the second. This function will then evaluate all list elements and only return those that satisfy the condition. In our case, if we aim to weed out even values, we can define a function isOdd() that returns True for odd numbers. Using this function with filter, we can seamlessly remove all even numbers from the list.
Let’s see the complete example,
def isOdd(number): # Function to check if a number is odd return number % 2 != 0 # A List of Numbers sampleList = [45, 67, 22, 45, 22, 89, 71, 22, 51] print("Original List:", sampleList) # Removing all even numbers from list sampleList = list(filter(isOdd, sampleList)) print("List after removing even numbers:") print(sampleList)
Output
Original List: [45, 67, 22, 45, 22, 89, 71, 22, 51] List after removing even numbers: [45, 67, 45, 89, 71, 51]
Summary
Today, we learned about remove elements from a list in Python based on a certain condition.