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

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

    The short answer is look here: https://wiki.python.org/moin/TimeComplexity

    With no arguments to pop its O(1)

    With an argument to pop:

    • Average time Complexity O(k) (k represents the number passed in as an argument for pop
    • Amortized worst case time complexity O(k)
    • Worst case time complexity O(n)

    Average time complexity:

    • Any time you put in a value the time complexity of that operation is O(n - k).

    • For example, if you have a list of 9 items than removing from the end of the list is 9 operations and removing from the beginning of the list is 1 operations (deleting the 0th index and moving all the other elements to their current index - 1)

    • Since n - k for the middle element of a list is k operations the average can be shortened to O(k).

    • Another way to think about this is that imagine that each index was removed from your 9 item list once. That would be a total of 45 operations. (9+8+7+6+5+4+3+2+1 = 45)

    • 45 is equal to O(nk) and since the pop operation occurred O(n) times you divide nk by n to get O(k)

    Amortized Worst Case Time Complexity

    • Imagine you have a list of 9 items again. Imagine you're removing every item of the list and the worst case occurs and you remove the first item of the list each time.

    • Since the list shrinks by 1 each time the number of total operations decreases each time from 9 through 1.

    • 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 = 45. 45 equals O(nk). Since you made 9 operations and 9 is O(n) to calculate the amortized worst case scenario you do O(nk) / O(n) which equals O(k)

    • Stating it's O(n) for the average and amortized worst case time complexity is also sort of correct. Notice that O(k) is approximately O(1/2n) and dropping the constant equals O(n)

    Worst Case Time Complexity

    • Unlike with amortized worst case time complexity you don't factor in the state of the data structure and just think about the worst case for any individual operation.
    • In that instance, the worst case is you have to remove the 1st item from the list which is O(n) time.

    Here's what I wrote to think this through in case it helps:

提交回复
热议问题