Why is "for ... in ..." MASSIVELY slower than "list.index()"?

Viewed 179

Comparing execution times of search algorithms in a list I came up to a result that list.index() is VERY much faster than a simple for in. According to this they should be both O(n). I have this results in my tests:

The simple solution passes about 350 Tests within 3 seconds:

def linear_simple(arr):
    for i in range(len(arr)):
        if arr[i] == #my searched value#:
            return i

The index solution passes all 2000 tests within 3 seconds (actually it is done even within 2 seconds):

def linear_index(arr):
    return arr.index( #my searched value# )

All test arrays are randomly generated. The tests were made several times with similar results.

That means index() is about 9 times faster. Why? Is index() not simply iterating the same way over the list like for in?

1 Answers

As Chris_Rands said, list.index is implemented in C. As it is compiled and not interpreted, code runs way faster.

Anyways, you can optimize your code a bit :

def linear_simple(arr, value):
    for i, e in enumerate(arr):
        if e == value:
            return i

This code runs faster on my computer (but not as fast as list.index)

Related