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

Idiom #119 Deduplicate list

Remove duplicates from list x.
Explain if original order is preserved.

Illustration
(distinct x)
(distinct x)
#include <algorithm>
#include <vector>
std::sort(x.begin(), x.end());
auto last = std::unique(x.begin(), x.end());
x.erase(last, x.end());
#include <string>
#include <unordered_set>
#include <vector>
std::vector<std::string> x = {"one", "two", "two", "one", "three"};
std::unordered_set<std::string> t;
for (auto e : x)
    t.insert(e);
using System.Collections.Generic;
using System.Linq;
var uniques = x.Distinct().ToList();
import std.algorithm;
import std.array;
x = x.sort.uniq.array;
import std.container;
import std.array;
x = redBlackTree(x)[].array;
x = x.toSet().toList();
Enum.uniq([1,26,3,40,5,6,6,7])
S = sets:from_list(X),
sets:to_list(S).
seen := make(map[T]bool)
j := 0
for _, v := range x {
	if !seen[v] {
		x[j] = v
		j++
		seen[v] = true
	}
}
for i := j; i < len(x); i++ {
	x[i] = nil
}
x = x[:j]
y := make(map[T]struct{}, len(x))
for _, v := range x {
	y[v] = struct{}{}
}
x2 := make([]T, 0, len(y))
for _, v := range x {
	if _, ok := y[v]; ok {
		x2 = append(x2, v)
		delete(y, v)
	}
}
x = x2
seen := make(map[T]bool)
j := 0
for _, v := range x {
	if !seen[v] {
		x[j] = v
		j++
		seen[v] = true
	}
}
x = x[:j]
import Data.List (sort)
nub $ sort x
const seen = new Set();
x = x.filter( v => {
  if(seen.has(v))
    return false;
  seen.add(v);
  return true;
});
x = [...new Set(x)];
x = Array.from(new Set(x));
import java.util.HashSet;
import java.util.Iterator;
final HashSet<T> seen = new HashSet<T>();
final Iterator<T> listIt = x.iterator();
while (listIt.hasNext()) {
  final T curr = listIt.next();
  if (seen.contains(curr)) {
    listIt.remove();
  } else {
    seen.add(curr);
  }
}
import java.util.HashSet;
import java.util.ArrayList;
x = new ArrayList<T>(new HashSet<T>(x));
import java.util.HashSet;
import java.util.List;
import java.util.Set;
Set<T> uniques = new HashSet<>(x);
x.clear();
x.addAll(uniques);
val duplicates = listOf("b", "a", "b", "c")
val noDuplicates = duplicates.distinct()
val duplicates = listOf("b", "a", "b", "c")
val noDuplicates = duplicates.toSet().toList()
(remove-duplicates x)
$x = array_unique($x);
uses classes;
var
  list: TList;
begin
  for i:= list.count-1 downto 0 do
    if list.indexOf(list.items[i]) <> -1 then
      list.delete(i);
end;
use List::MoreUtils 'uniq';
@x = uniq(@x);
from collections import OrderedDict
x = list(OrderedDict(zip(x, x)))
x = list(set(x))
x.uniq!
x.sort();
x.dedup();
x = x.distinct
x = x.Distinct.ToList

Do you know the best way to do this in your language ?
New implementation...

Idiom created by

programming-idioms.org

Related idioms