What is the time complexity of popping elements from list in Python?

前端 未结 4 946
情书的邮戳
情书的邮戳 2020-11-27 03:35

I wonder what is the time complexity of pop method of list objects in Python (in CPython particulary). Also does the value of N for list.pop(N) affects the complexity?

4条回答
  •  旧巷少年郎
    2020-11-27 04:34

    It should be O(1) with L.pop(-1), and O(n) with L.pop(0)

    see following example:

    from timeit import timeit
    if __name__ == "__main__":
        L = range(100000)
        print timeit("L.pop(0)",  setup="from __main__ import L", number=10000)
        L = range(100000)
        print timeit("L.pop(-1)", setup="from __main__ import L", number=10000)
    
    >>> 0.291752411828
    >>> 0.00161794329896
    

提交回复
热议问题