Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is faster for searching items in list, in operator or index()?

From this site, it says that list.index() is a linear search through the list.

And it also seems like in is also linear.

Is there any advantage to using one over the other?

like image 514
Thomas T Avatar asked Dec 08 '22 19:12

Thomas T


1 Answers

If you want to compare different python approaches, such as the in operator versus .index(), use the timeit module to test the speed differences. Python data type complexities are documented on http://wiki.python.org/moin/TimeComplexity.

Do note that there is a big difference between in and .index(); the first one returns a boolean, the latter the index of the found item (an integer) or it'll raise an exception. It thus is (slightly) slower for the average case:

$ python -mtimeit -s 'a = list(range(10000))' '5000 in a'
10000 loops, best of 3: 107 usec per loop
$ python -mtimeit -s 'a = list(range(10000))' 'a.index(5000)'
10000 loops, best of 3: 111 usec per loop

If you need to optimize for membership testing, use a set() instead:

$ python -mtimeit -s 'a = set(range(10000))' '5000 in a'
10000000 loops, best of 3: 0.108 usec per loop
like image 173
Martijn Pieters Avatar answered Dec 11 '22 09:12

Martijn Pieters