The complexity of len()
with regards to sets and lists is equally O(1). How come it takes more time to process sets?
~$ python -m timeit \"a=[1,2,3,
Many have noted that O(1) is not about performance on different data types, but about performance as a function of different input sizes.
If you're trying to test O(1)-ness, you'd be looking for something more like
~$python -m timeit --setup "a=list(range(1000000))" "len(a)"
10000000 loops, best of 3: 0.198 usec per loop
~$python -m timeit --setup "a=list(range(1))" "len(a)"
10000000 loops, best of 3: 0.156 usec per loop
Big data or little data, the time taken is quite similar. Per other posts, this separates setup time from testing time, but doesn't go as far as to reduce noise of len-time vs loop-time.