I am learning python and was checking out the timeit
module. I am trying the exact same thing with the list
, set
and tuple
to check the overheads involved. Please take a gander (IPython shell) :-
>>> timeit {x**9 for x in range(100)}
>>> 49.3 µs ± 229 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
>>> timeit (x**9 for x in range(100))
>>> 830 ns ± 6.39 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
>>> timeit [x**9 for x in range(100)]
>>> 45.8 µs ± 346 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
I get that tuple
comprehension is fastest because it doesn't have any of the overhead of set
and list
, eg. hash
calculation and duplicate removal in set
or order preservation of elements in list
.
But what I do not understand is that the set comprehension
and list comprehension
take almost equivalent time. I want to know why is the set comprehension
is not very much slower than the list comprehension
as in a set
, the compiler has the overhead of computing the hash value
of every entry and check for duplicates while list comprehension
don't have to.
Thanks in advance for your time.