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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With