This language bar is your friend. Select your favorite languages!
Select your favorite languages :
- Or search :
Idiom #136 Remove all occurrences of a value from a list
Remove all occurrences of the value x from list items.
This will alter the original list or return a new list, depending on which is more idiomatic.
- Clojure
- C++
- C#
- D
- Dart
- Elixir
- Fortran
- Go
- Go
- Go
- Go
- Go
- Haskell
- JS
- Java
- Java
- Java
- Lisp
- PHP
- Pascal
- Perl
- Python
- Python
- Python
- Python
- Python
- Python
- Ruby
- Rust
- Rust
- Scala
- Smalltalk
items2 := make([]T, 0, len(items))
for _, v := range items {
if v != x {
items2 = append(items2, v)
}
}
This is simple and runs in linear time.
However, it allocates memory for the new slice items2.
T is the type of the elements.
However, it allocates memory for the new slice items2.
T is the type of the elements.
func removeAll[S ~[]T, T comparable](items *S, x T) {
j := 0
for i, v := range *items {
if v != x {
(*items)[j] = (*items)[i]
j++
}
}
var zero T
for k := j; k < len(*items); k++ {
(*items)[k] = zero
}
*items = (*items)[:j]
}
The type parameter T has a constraint: it must be comparable with ==
In case T contains pointers, zeroing discarded elements helps garbage collection.
In case T contains pointers, zeroing discarded elements helps garbage collection.
j := 0
for i, v := range items {
if v != x {
items[j] = items[i]
j++
}
}
for k := j; k < len(items); k++ {
items[k] = nil
}
items = items[:j]
This filters items in-place in linear time.
The "tail" elements are set to nil to leverage garbage collection, avoiding a memory leak.
The "tail" elements are set to nil to leverage garbage collection, avoiding a memory leak.
j := 0
for i, v := range items {
if v != x {
items[j] = items[i]
j++
}
}
items = items[:j]
This filters items in-place in linear time.
But don't use it with pointer elements, because you would have a memory leak at the end of the underlying array.
But don't use it with pointer elements, because you would have a memory leak at the end of the underlying array.
filter (/= x) items
This returns a new list.
/= is the inequality operator of Haskell. Note that its usage requires x's type to instantiate the Eq type-class.
(/= x) is a shorthand for the lambda (\e -> e /= x).
/= is the inequality operator of Haskell. Note that its usage requires x's type to instantiate the Eq type-class.
(/= x) is a shorthand for the lambda (\e -> e /= x).
items.removeAll(Collections.singleton(x));
items has type java.util.List.
items is altered by removeAll().
items is altered by removeAll().
Iterator<T> i = items.listIterator();
while (i.hasNext())
if (i.next().equals(x)) i.remove();
(remove-if (lambda (val) (= val x)) items)
Functional implementation that returns a new list. = function assumes that items is a list of numbers.