Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python remove elements that are greater than a threshold from a list

Tags:

python

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)
like image 351
Mel Avatar asked Jan 27 '20 05:01

Mel


People also ask

How do you remove something from the middle of a list in Python?

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.

What does .remove do in Python?

The remove() method removes the first occurrence of the element with the specified value.

Can you remove multiple items from a list Python?

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.


2 Answers

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 :-)

like image 63
Raymond Hettinger Avatar answered Oct 23 '22 15:10

Raymond Hettinger


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.


Regular example

a = [1, 9, 2, 10, 3, 6]

filtered = filter(lambda num: num > 5, a)
print(list(filtered))

Output: [9, 10, 6]


Tuple example

a = [
    ['Data1', 1],
    ['Data2', 9],
    ['Data3', 2],
]

filtered = filter(lambda num: num[1] > 5, a)
print(list(filtered))

Output: [['Data2', 9]]

like image 44
Crystal Avatar answered Oct 23 '22 14:10

Crystal