I would like to remove elements that are greater than a threshold from a list.
For example, a list with elements a = [1,9,2,10,3,6]
.
I would like to remove all elements that are greater than 5.
Return should be [1,2,3].
I tried using enumerate and pop but it doesn't work.
for i,x in enumerate(a):
if x > 5:
a.pop(i)
The pop() method removes an element at a given index, and will also return the removed item. You can also use the del keyword in Python to remove an element or slice from a list.
The remove() method removes the first occurrence of the element with the specified value.
Multiple elements can be deleted from a list in Python, based on the knowledge we have about the data. Like, we just know the values to be deleted or also know the indexes of those values.
Try using a list comprehension:
>>> a = [1,9,2,10,3,6]
>>> [x for x in a if x <= 5]
[1, 2, 3]
This says, "make a new list of x values where x comes from a but only if x is less than or equal to the threshold 5.
The issue with the enumerate() and pop() approach is that it mutates the list while iterating over it -- somewhat akin to sawing-off a tree limb while your still sitting on the limb. So when (i, x)
is (1, 9)
, the pop(i) changes a to [1,2,10,3,6]
, but then iteration advances to (2, 10)
meaning that the value 2 never gets examined. It falls apart from there.
FWIW, if you need to mutable the list in-place, just reassign it with a slice:
a[:] = [x for x in a if x <= 5]
Hope this helps :-)
You can also use the filter()
function along with a lambda
function, which could work better for something that is tuple and not just a list.
a = [1, 9, 2, 10, 3, 6]
filtered = filter(lambda num: num > 5, a)
print(list(filtered))
Output: [9, 10, 6]
a = [
['Data1', 1],
['Data2', 9],
['Data3', 2],
]
filtered = filter(lambda num: num[1] > 5, a)
print(list(filtered))
Output: [['Data2', 9]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With