Sunday, November 25, 2018

How to remove duplicates from Python list and keep order?

If you want to keep order of the original list, just use OrderedDict with None as values.



In Python2:




    from collections import OrderedDict
from itertools import izip, repeat

unique_list = list(OrderedDict(izip(my_list, repeat(None))))


In Python3 it's even simpler:



    from collections import OrderedDict

from itertools import repeat

unique_list = list(OrderedDict(zip(my_list, repeat(None))))


If you don't like iterators (zip and repeat) you can use a generator (works both in 2 & 3):



    from collections import OrderedDict
unique_list = list(OrderedDict((element, None) for element in my_list))

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...