Logo

Programming-Idioms

  • 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.

import java.util.List;
items.stream().findFirst().filter(item -> "x".equals(item)).ifPresent(removeIndex -> items.remove(removeIndex));
import java.util.Iterator;
import java.util.List;
<T> void remove(List<T> items, T x) {
    Iterator<T> i = items.listIterator();
    while (i.hasNext())
        if (i.next() == x) {
            i.remove();
            break;
        }
}
import java.util.ArrayList;
T value;
for(int index = 0; index < items.size(); index++) {
	value = items.get(index);
	if(value.equals(x)) {
		items.remove(index);
		break;
	}
}

Subsequent items will be shifted to the left.
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.
(let [[n m]
      (split-with (partial not= x) items)]
  (concat n (rest m)))

New implementation...