Performance comparison: insert vs build Python set operations

前端 未结 4 419
时光说笑
时光说笑 2021-02-02 17:14

In python, is it faster to a) Build a set from a list of n items b) Insert n items into a set?

I found this page (http://wiki.python.org/moin/TimeComplexity) but it did

4条回答
  •  北荒
    北荒 (楼主)
    2021-02-02 18:06

    Here are the results from running the comparison using timeit. Seems initialization of set using list to be faster, curious to know why it is so:

    from timeit import timeit
    timeit("set(a)","a=range(10)")
    # 0.9944498532640864
    
    timeit("for i in a:x.add(i)","a=range(10);x=set()")
    # 1.6878826778265648
    

    Python version: 2.7

提交回复
热议问题