The easiest way is to convert it to a set, because sets, by definition, don't have duplicates:
numbers = [1, 2, 1, 2]
s = set(numbers)
print(len(s))
This will print 2
in the screen.
You can always convert it back to a list afterwards if you need to. Note, however, that sets are unordered, so your list will lose its order:
numbers = list(set(numbers))
If you need to keep the order, one solution is to construct a new list:
numbers = [1, 2, 1, 2]
no_dups = []
for n in numbers:
if n not in no_dups:
no_dups.append(n)
print(no_dups)
However this is slow for large lists, because n not in no_dups
takes linear
time to run, since it requires a scan through the whole list. To speed that
check up, you could create a set: seen = set()
and put numbers in it and use
n not in seen
. The reason this results in a speedup is that checking if an
item is in a set takes constant time in Python.