SESK: Stuff Everyone Should Know · sesk.info/tech-list-insert-front-slow
Why is inserting at the front of a Python list slow when appending at the end is fast?
Every other item has to shift over by one, because a list is an array underneath.
- Python checks the whole list for duplicates
- The list must be re-sorted
- Every other item must shift over one spot ✔
Why: A Python list stores slots side by side. An append usually uses spare space and is amortized O(1), but adding at the front means shifting every existing item one slot, which is O(n).
Huh, didn't know that: Python's collections.deque was built for fast adds and removes at both ends.
I cut to the front of the Python list. Everyone behind me had to shuffle, and they were not happy.
Like this card?
References
Answer: Every other item must shift over one spot. A Python list stores slots side by side. An append usually uses spare space and is amortized O(1), but adding at the front means shifting every existing item one slot, which is O(n).
- Python Tutorial: Data Structures docs.python.org/3/tutorial/datastructures.html
doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one).
Checked 2026-10-10.
Think this answer is wrong? Tap "Challenge this answer" on the card in the game and tell us why.
More stuff everyone should know
That's stuff everyone should know.