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 itera
Starting Python 3.8
, and the introduction of assignment expressions (PEP 572) (:=
operator), we can use and increment a variable within a list comprehension:
# items = [1, 10, 2, 9, 3, 8, 4, 7]
total = 0
[x for x in items if not (x < 5 and (total := total + 1) <= 3)]
# [10, 9, 8, 4, 7]
This:
total
to 0
which will symbolize the number of previously matched occurrences within the list comprehensionx < 5
)total
(total := total + 1
) via an assignment expressiontotal
to the max number of items to discard (3
)