Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

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.ArrayList;
T value;
for(int index = 0; index < items.size(); index++) {
	value = items.get(index);
	if(value.equals(x)) {
		items.remove(index);
		break;
	}
}
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;
        }
}
(let [[n m]
      (split-with (partial not= x) items)]
  (concat n (rest m)))
erase(items, x);
using System.Collections.Generic;
items.Remove(x);
import std.algorithm;
items = items.remove(items.countUntil!(a => a == x));
items.remove(x);
List.delete(items, x)
integer, dimension(:), allocatable :: items

i = findloc(items, x)
if (i /= 0) items = [items(1:i-1), items(i+1:)]
import "slices"
func removeFirstByValue[S ~[]T, T comparable](items *S, x T) {
	for i, y := range *items {
		if y == x {
			*items = slices.Delete(*items, i, i+1)
			return
		}
	}
}
for i, y := range items {
	if y == x {
		items = append(items[:i], items[i+1:]...)
		break
	}
}
import "slices"
func removeFirstByValue[S ~[]T, T comparable](items *S, x T) {
	if i := slices.Index(*items, x); i != -1 {
		*items = slices.Delete(*items, i, i+1)
	}
}
for i, y := range items {
	if y == x {
		copy(items[i:], items[i+1:])
		items[len(items)-1] = nil
		items = items[:len(items)-1]
		break
	}
}
import Data.List
delete x items
const idx = items.indexOf(x)
if (idx !== -1) items.splice(idx, 1)
$list_position = array_search($x, $items);
$specific_item = $items[$position];
unset($specific_item);
uses classes;
i := items.IndexOf(x);
if i <> -1 then
  items.delete(i);
use List::UtilsBy qw(extract_first_by);
extract_first_by { $x eq $_ } @items;
items.remove(x)
i = items.index(x)
items.delete_at(i) unless i.nil?
if let Some(i) = items.iter().position(|item| *item == x) {
    items.remove(i);
}

New implementation...