The shortest way to remove duplicates and keep the original order is list(dict.fromkeys(items)).
The program
numbers = [3, 1, 3, 2, 1, 5, 2] unique = list(dict.fromkeys(numbers)) print("Original:", numbers) print("Unique: ", unique)
Original: [3, 1, 3, 2, 1, 5, 2] Unique: [3, 1, 2, 5]
How it works
dict.fromkeys(numbers)builds a dictionary with each number as a key. A dictionary cannot have the same key twice, so repeated numbers are stored only once.- Dictionaries keep keys in the order they were first added, so 3 stays first.
list(...)turns the keys back into a list.
Another way: set()
set(numbers) also removes duplicates, but a set has no fixed order. Use it when the order does not matter, and sort the result if you want a predictable order:
numbers = [3, 1, 3, 2, 1, 5, 2] print(sorted(set(numbers)))
[1, 2, 3, 5]
Ignoring upper and lower case
With a loop you can decide what counts as "the same". Here "Ada" and "ada" count as one name, and the first spelling is kept:
names = ["Ada", "Linus", "ada", "Grace", "LINUS"] seen = set() unique = [] for name in names: key = name.lower() if key not in seen: seen.add(key) unique.append(name) print(unique)
['Ada', 'Linus', 'Grace']
Checking key not in seen is fast because seen is a set. Checking in on a list gets slower as the list grows.