What is the proper way to track indexes in python?

By : John
Source: Stackoverflow.com
Question!

Right now I am tracking my index in side the loop like this

index = 0
for entry in longList:
    if entry == 'foo':
        print index
    index += 1

is there a better way to do this?

By : John


Answers

Using enumerate would be a better idea.

for ind,item in enumerate(longList):
    if item == 'foo':
        print ind


If your list is really long and static, you should consider using a lookup table (actually, a dictionary of index lists with the entry as the key). It will almost pay for itself after the first search, since you currently always iterate over all the elements.

from collections import defaultdict

# Create and fill the table (only once or whenever the list changes)
lookupTable = defaultdict(list)
for index, entry in enumerate(longList):
    lookupTable[entry].append(index)

# Search the list (as many times as you want)
indexes = lookupTable.get('foo')
# and you get either 'None' or a list of indexes '[1,10,20]'
By : alexisdm


Yes, the best way is to do this:

longList.index('foo')
By : Sam


This video can help you solving your question :)
By: admin