Question
searching performance in list is better than in set
Searching an element in a 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 are 48.3 msec in the set vs 28 msec in the list, which shows searching in a list is faster than searching in a set and contradicts 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
Could you help me understand why the performance of searching sequence in a list is better than in a set in Python?
I cannot understand.