3

How set is much much faster in lookup for an element than list, is that something to do with the ordered maintain in list ? or is the lookup algorithm is different in set than list ?

>>> from timeit import Timer    
>>> Timer("100042 in L", "L=range(100000)").timeit(number=10000)
21.69940710067749
>>>
>>> Timer("100042 in S", "S=set(range(100000))").timeit(number=10000)
0.0006740093231201172
>>>

Some one pleae point me out any link or algorithm used between the two ?

James Sapam
  • 16,036
  • 12
  • 50
  • 73

1 Answers1

7

set uses hashing (it allows only items which are hashable), which will be much faster than list's sequential access, for random lookup.

But, list might beat set, if the item being searched is at the beginning.

from timeit import Timer
print Timer("0 in L", "L=range(100000)").timeit(number=10000)
print Timer("0 in S", "S=set(range(100000))").timeit(number=10000)

Output on my machine

0.00127078635541
0.00143169642464

Edit: Time complexity of different operations on various objects are documented here. Thanks @mgilson :)

thefourtheye
  • 233,700
  • 52
  • 457
  • 497