.Maui Blog

Python remove duplicates from lists

Let’s take a list like this as an example:

numbers = [i for i in xrange(1,11)] + [i for i in xrange(1,8)]

To remove duplicates in the numbers list you could use this code:

uk_numbers = []
for n in numbers:
    if n not in uk_numbers:
        uk_numbers.append(n)

Or get the same result with a single line of code:

uk_numbers = list(set(numbers))

The latter method transforms the number list into a set, an object that does not allow duplicates, and then returns it to a list.

Exit mobile version