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

21,420

Solution 1

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

Solution 2

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]]

Share:
21,420

Related videos on Youtube

Author by

Mel

Updated on November 02, 2021

Comments

  • Mel over 1 year

    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)
    
    • Mark
      Mark about 3 years
      You would typically make a new list with something like a = [n for n in a if n < 5]
  • Karl Knechtel
    Karl Knechtel about 3 years
    Beautiful answer, as expected from a core dev. I often see a lot of resistance to the idea of showing list comprehensions to beginners; but I honestly believe that - with a proper grounding - they are easier to understand (for the tasks where they're appropriate) than the corresponding loop.

Related