3 ms·
Lists, being an "asymmetrical" recursive data structure, have O(1) time for adding an element to its head but O(n) time for sticking an element to its tail Wel
by icebraining 13y ago
Lists, being an "asymmetrical" recursive data structure, have O(1) time for adding an element to its head but O(n) time for sticking an element to its tail
Well, a list is an abstract data structure. Being Python, it's implemented as an array, so adding an element to the head actually costs O(n) - since all elements must be copied to the next position - while appending to the tail is O(1) (amortized, since in certain cases it triggers a full resize, requiring a full new copy of the list).
The language wiki has a page with the time complexity of a few of its data structures: https://wiki.python.org/moin/TimeComplexity https://wiki.python.org/moin/TimeComplexity
- eru 13y agoThanks for the insight. By the way, you could make Python's list's adding of one element at the back worst case O(1), too, if you were willing to waste some space.
- dschiptsov 13y agoYes, my inaccuracy - I considered them from the classic Lisps point of view. The trade-offs they made in Python about list's implementation are disputable.)