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:
- We have defined a Python List(numbers).
- Using List comprehension we are only returning elements that are less than 4 and assigning the newly created list to the numbers list variable.
- 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?
Similar Posts
- Django send post request with different field than primary key.
- Replace DataFrame column values with a specific value
- Get count of a specific element in a list using Python
- Add item at a specific position in a Python List
- remove rows base on NaN of specific column
- Remove all items from a list in Python
- Remove duplicate items from a list in Python