Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove the first N items that match a condition in a Python list

If I have a function matchCondition(x), how can I remove the first n items in a Python list that match that condition?

One solution is to iterate over each item, mark it for deletion (e.g., by setting it to None), and then filter the list with a comprehension. This requires iterating over the list twice and mutates the data. Is there a more idiomatic or efficient way to do this?

n = 3  def condition(x):     return x < 5  data = [1, 10, 2, 9, 3, 8, 4, 7] out = do_remove(data, n, condition) print(out)  # [10, 9, 8, 4, 7] (1, 2, and 3 are removed, 4 remains) 
like image 849
Thomas Johnson Avatar asked Sep 19 '16 18:09

Thomas Johnson


People also ask

How do I remove a matching element from a list in Python?

The remove() method removes the first matching element (which is passed as an argument) from the list. 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.

How do I remove the first element from a list?

The remove() function allows you to remove the first instance of a specified value from the list. This can be used to remove the list's top item. Pick the first member from the list and feed it to the remove() function.

How do I remove a specific index from a list in Python?

You can use the pop() method to remove specific elements of a list. pop() method takes the index value as a parameter and removes the element at the specified index. Therefore, a[2] contains 3 and pop() removes and returns the same as output. You can also use negative index values.


1 Answers

One way using itertools.filterfalse and itertools.count:

from itertools import count, filterfalse  data = [1, 10, 2, 9, 3, 8, 4, 7] output = filterfalse(lambda L, c=count(): L < 5 and next(c) < 3, data) 

Then list(output), gives you:

[10, 9, 8, 4, 7] 
like image 134
Jon Clements Avatar answered Oct 14 '22 20:10

Jon Clements