Firstly, you did not measure the speed of len() , you measured the speed of creating a list / set along with the speed of len() .
Use the --setup timeit argument:
$ python -m timeit --setup "a=[1,2,3,4,5,6,7,8,9,10]" "len(a)" 10000000 loops, best of 3: 0.0369 usec per loop $ python -m timeit --setup "a={1,2,3,4,5,6,7,8,9,10}" "len(a)" 10000000 loops, best of 3: 0.0372 usec per loop
Statements that you pass --setup are executed before the speed measurement len() .
Secondly, it should be noted that len(a) is a fairly fast operator. The process of measuring its speed may be “noise”. Note that code executed (and measured) in time is equivalent to the following:
for i in itertools.repeat(None, number): len(a)
Since both len(a) and itertools.repeat(...).__next__() are fast operations, and their speeds may be similar, the speed of itertools.repeat(...).__next__() can affect the timings.
For this reason, you better measure len(a); len(a); ...; len(a) len(a); len(a); ...; len(a) len(a); len(a); ...; len(a) (repeated 100 times or so) so that the body of the for loop takes a significantly longer amount of time than the iterator:
$ python -m timeit --setup "a=[1,2,3,4,5,6,7,8,9,10]" "$(for i in {0..1000}; do echo "len(a)"; done)" 10000 loops, best of 3: 29.2 usec per loop $ python -m timeit --setup "a={1,2,3,4,5,6,7,8,9,10}" "$(for i in {0..1000}; do echo "len(a)"; done)" 10000 loops, best of 3: 29.3 usec per loop
(The results still say that len() has the same characteristics in lists and sets, but now you are sure that the result is correct.)
Thirdly, it is true that “complexity” and “speed” are related, but I think you are confused. The fact that len() has O (1) complexity for lists and sets does not mean that it should work at the same speed in lists and sets.
This means that on average, no matter how long the list a , len(a) performs the same asymptotic number of steps. And no matter how long b set, len(b) performs the same asymptotic number of steps. But the algorithm for calculating the size of lists and sets may be different, which leads to different characteristics (timeit shows that this is not so, however this may be an opportunity).
Finally,
If creating a given object takes longer than creating a list, what will be the main reason?
A set, as you know, does not allow repeating elements. Sets in CPython are implemented as hash tables (to provide averaging and O (1) lookups): building and maintaining a hash table is much more complicated than adding items to the list.
In particular, when building a set, you need to calculate hashes, build a hash table, look at it to avoid inserting recurring events, etc. In contrast, lists in CPython are implemented as a simple array of pointers, which are malloc() ed and realloc() ed if necessary.