Complexity of len() with regard to sets and lists

前端 未结 7 1548
耶瑟儿~
耶瑟儿~ 2021-02-04 23:38

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,         


        
7条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-05 00:23

    Use this with the -s flag to timeit without taking into account the first string:

    ~$ python -mtimeit -s "a=range(1000);" "len(a)"
    10000000 loops, best of 3: 0.0424 usec per loop
                               ↑ 
    

    ~$ python -mtimeit -s "a={i for i in range(1000)};" "len(a)"
    10000000 loops, best of 3: 0.0423 usec per loop
                               ↑ 
    

    Now it's only considering only the len function, and the results are pretty much the same since we didn't take into account the creation time of the set/list.

提交回复
热议问题