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

前端 未结 4 966
情书的邮戳
情书的邮戳 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:22

    Pop() for the last element ought to be O(1) since you only need to return the element referred to by the last element in the array and update the index of the last element. I would expect pop() for an arbitrary element to be O(N) and require on average N/2 operations since you would need to move any elements beyond the element you are removing one position up in the array of pointers.

提交回复
热议问题