Nathan Miller Nathan Miller - 24 days ago 9
Python Question

Get indexes for first occurrence of each element in a list?

I have a list of about 90k elements (about 670 unique). I would like to get the indexes for the first occurrence of each value. I have just tried a list comprehension like this:

In: [["foo", "bar", "baz", "bar", "foo"].index(x) for x in ["foo", "bar", "baz", "bar", "foo"]]
Out: [0, 1, 2, 1, 0]


This works, but it takes a couple of minutes to run on my machine. What is a better (faster) way to do this?

Answer

I think you just want to use enumerate (unless you want the first occurrence of each item in the list):

strings = ["foo", "bar", "baz", "bar", "foo"]
for index, value in enumerate(strings):
    print index, value

outputs

0 foo
1 bar
2 baz
3 bar
4 foo

If you wanted, for example, 1 bar instead of 3 bar, you can maintain a dictionary of found strings:

for index, value in enumerate(strings):
    if value not in d:
        d[value] = index

for value in strings:
    print value, d[value]