Based on this older thread, it looks like the cost of list functions in Python is:
- Random access: O(1)
- Insertion/deletion to front: O(n)
- Insertion/deletion to back: O(1)
Can anyone confirm whether this is still true in Python 2.6/3.x?
Based on this older thread, it looks like the cost of list functions in Python is:
Can anyone confirm whether this is still true in Python 2.6/3.x?
Take a look here. It's a PEP for a different kind of list. The version specified is 2.6/3.0.
Append (insertion to back) is
O(1)
, while insertion (everywhere else) isO(n)
. So yes, it looks like this is still true.Fwiw, there is a faster (for some ops... insert is O(log n)) list implementation called BList if you need it. BList
That's correct, inserting in front forces a move of all the elements to make place.
collections.deque
offers similar functionality, but is optimized for insertion on both sides.I know this post is old, but I recently did a little test myself. The complexity of list.insert() appears to be O(n)
Code:
See 5 positions where insertion can be done. Cost is of course a function of how large the list is, and how close you are to the beginning of the list (i.e. how many memory locations have to be re-organized)
Ignore left image of plot
Python 3 is mostly an evolutionary change, no big changes in the datastructures and their complexities.
The canonical source for Python collections is TimeComplexity on the Wiki.