Searching an element in set takes O(1) time complexity, while searching in a list takes O(n) time complexity. The n is the number of elements in a set or list.
In my test on the real searching time cost, the n is set to 1,000,000 which I believe is a big number. The test results is 48.3 msec in set vs 28 msec in list, which shows searching in a list is faster than searching in a set and contradicts with the time complexity analysis. I tried increasing n and comparing the searching speed, and it turns out that the finding holds true until I get a memory error when n is very big.
(base) PS C:Users> python -m timeit -n 100 “300 in set(range(1000000))”
100 loops, best of 5: 48.3 msec per loop
(base) PS C:Users> python -m timeit -n 100 “300 in list(range(1000000))”
100 loops, best of 5: 28 msec per loop
time cost results
Could you help me understand why performance of searching sequence in a list is better than in a set in python?
I cannot understand.
Simon Wang is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.