[python]Remove duplicates from a list

I have learned something interesting… removing duplicates in a list is actually quite easily achieved without using iteration…

from collections import OrderedDict

a = ["1", 1, 2, 3, "3", "3", "4"]
b = list(set(a))

c = list(OrderedDict.fromkeys(a))
print("Unordered non-duplicated list {}\n".format(b))
print("Ordered non-duplicated list {}, preserved the list of the original a".format(c))

The output is self explanatory, you use set if you do not bother about the order, you use Ordereddict if you need to preserve the original order.

Unordered non-duplicated list [1, 2, 3, '4', '3', '1']

Ordered non-duplicated list ['1', 1, 2, 3, '3', '4'], preserved the list of the original a

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s