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

From this site it is said that list.index () is a linear search on a list.

And it also seems that in also linear.

Is there an advantage to using one over the other?

+4
source share
1 answer

If you want to compare different python approaches, such as the in and .index() timeit , use the timeit module to check the speed difference. The complexities of Python data types are documented at http://wiki.python.org/moin/TimeComplexity .

Note that there is a big difference between in and .index() ; the first returns a logical value, the second returns the index of the element found (integer) or throws an exception. So for the average case this is (slightly) slower:

 $ 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 membership testing, use set() instead:

 $ python -mtimeit -s 'a = set(range(10000))' '5000 in a' 10000000 loops, best of 3: 0.108 usec per loop 
+13
source

Source: https://habr.com/ru/post/1448079/


All Articles