Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove duplicates in python list but remember the index

How can I remove duplicates in a list, keep the original order of the items and remember the first index of any item in the list?

For example, removing the duplicates from [1, 1, 2, 3] yields [1, 2, 3] but I need to remember the indices [0, 2, 3].

I am using Python 2.7.

like image 515
kklw Avatar asked Feb 15 '26 13:02

kklw


1 Answers

I'd tackle this a little differently and use an OrderedDict and the fact that a lists index method will return the lowest index of an item.

>>> from collections import OrderedDict
>>> lst = [1, 1, 2, 3]
>>> d = OrderedDict((x, lst.index(x)) for x in lst)
>>> d
OrderedDict([(1, 0), (2, 2), (3, 3)]

If you need the list (with its duplicates removed) and the indices separately, you can simply issue:

>>> d.keys()
[1, 2, 3]
>>> d.values()
[0, 2, 3]
like image 72
timgeb Avatar answered Feb 17 '26 01:02

timgeb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!