DEV Community

João M.C. Teixeira
João M.C. Teixeira

Posted on

Time needed to search in a list or set in Python

The time it takes to search an item in a list depends on the size of the list and the position of the item in it. While for set the time cost is maintained. Here, we do not consider the time needed to create the lists and sets.

l100 = list(range(100))
s100 = set(range(100))
l100k = list(range(100_000))
s100k = set(range(100_000))
Enter fullscreen mode Exit fullscreen mode
%%timeit
100 in l100
Enter fullscreen mode Exit fullscreen mode

895 ns ± 31.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%%timeit
100 in s100
Enter fullscreen mode Exit fullscreen mode

25.8 ns ± 1.56 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

%%timeit
100_000 in l100k
Enter fullscreen mode Exit fullscreen mode

874 µs ± 22.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%%timeit
100_000 in s100k
Enter fullscreen mode Exit fullscreen mode

25.6 ns ± 0.812 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

%%timeit
1 in l100k
Enter fullscreen mode Exit fullscreen mode

33.5 ns ± 0.589 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

%%timeit
1 in s100k
Enter fullscreen mode Exit fullscreen mode

26.4 ns ± 1.13 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

Top comments (0)