python

Remove items less than a specific value from Python list

The code examples explained in this post can be used to remove the elements less than a specific value from a list using Python.

# Using list comprehension
my_list = [10, 6, 11, 3, 8, 5, 14]
my_list = [x for x in my_list if x < 9]

print(my_list)

Output

[6, 3, 8, 5]

Using list comprehension to remove items less than a value

We are using list comprehension here to remove the elements that are less than a given value. We are removing thee items from a given Python list.

Code Example

numbers = [1, 5, 8, 9, 3, 7, 2]

numbers = [x for x in numbers if x < 4]

print(numbers)

Output

[1, 3, 2]

In the above code example:

  1. We have defined a Python List(numbers).
  2. Using List comprehension we are only returning elements that are less than 4 and assigning the newly created list to the numbers list variable.
  3. Print numbers list to check the output.

Using filter() and lambda functions

We can also use the filter() function to remove items from a list that is less than a specific value. Below is the code example that will help you to understand it.

numbers = [1, 5, 8, 9, 3, 7, 2]

numbers = filter(lambda val: val < 4, numbers)

print(list(numbers))

Output

[1, 3, 2]
Was this helpful?