fastest list index searching

Someone was looking for fastest list index searching (in Python) in stackoverflow. There are only four elements in the list, still it was as issue for him, as it was used in an inner-loop and the profiler identified that, this part was executing the most. He tried several approaches.

1. This is the most obvious one:
if value in mylist:
    return mylist.index(value)
Here the problem is, in the condition used in if, it takes O(n) time to check if the value is in the list, and the return statement - mylist.index(value), also takes O(n) time.

2. The second approach - I call it smart approach :
try:
    return mylist.index(value)
except ValueError:
    return None
This code gets rid of the condition check. But the try-except thing takes some time for the Python interpreter. I like this approach. In fact, if the list was large, I would prefer this.

3. The third approach - I guess it's more Pythonic?
for i, x in enumerate(mylist):
    if x == value:
         return i
return None

All the above solutions are OK. But he was looking for the fastest way. So, I gave the solution :
 if value == mylist[0]:
   return 0
 elif value == mylist[1]:
   return 1
 elif value == mylist[2]:
   return 2
 elif value == mylist [3]:
   return 3
Yes, it is the fastest among the discussed options. And he happily accepted the solution. :)

Here you can find the post : stackoverflow.com/questions/25476179/fastest-list-index-searching/

Comments

Unknown said…
why don't use directly:
indexes = [ i for i,e in enumerate(L) if e==v] ?

Popular posts from this blog

Strip HTML tags using Python

lambda magic to find prime numbers

Convert text to ASCII and ASCII to text - Python code