Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 918
Haldun Avatar asked Oct 12 '08 15:10

Haldun


People also ask

What is the time complexity for list pop in Python?

The time complexity of the python list pop() function is constant O(1). It does not matter how many elements are in the list, removing an element from a list takes the same time and it does not depend on the number of elements to be popped. The reason for this is that in cPython lists are implemented with arrays.

Is Pop slow in Python?

Python list. pop(0) is extremely slow for a large list.

What is the usage of pop () in list in Python?

Python list pop() is an inbuilt function in Python that removes and returns the last value from the List or the given index value.


2 Answers

Yes, it is O(1) to pop the last element of a Python list, and O(N) to pop an arbitrary element (since the whole rest of the list has to be shifted).

Here's a great article on how Python lists are stored and manipulated: http://effbot.org/zone/python-list.htm

like image 130
Dan Lenski Avatar answered Oct 16 '22 20:10

Dan Lenski


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.

like image 43
tvanfosson Avatar answered Oct 16 '22 22:10

tvanfosson