Logo

Programming-Idioms

  • C++
  • Python

Idiom #135 Remove item from list, by its value

Remove at most 1 item from list items, having the value x.
This will alter the original list or return a new list, depending on which is more idiomatic.
If there are several occurrences of x in items, remove only one of them. If x is absent, keep items unchanged.

del items[items.index(x)]
for i in range(len(items)):
    if items[i] == x:
        del items[i]
        break
items.remove(x)

Raises a ValueError if x is not found.
erase(items, x);

C++20
items has type std::list<>
(let [[n m]
      (split-with (partial not= x) items)]
  (concat n (rest m)))

New implementation...