Lesson 2 of 81950s–today7 min
Arrays versus linked lists
You have a Python list of ten million log lines and need to add each new line at the front. lines.insert(0, line) works, but every call moves ten million references one place to the right. The same program with collections.deque and appendleft does the work in constant time.
Nothing about the data changed. Only the way it was laid out in memory did, and that choice decides which operations are cheap and which are ruinous.
The rest of this lesson is part of Pro
Create a free account to read the first lesson of every path, and go Pro for the rest.
Sources
- TimeComplexity — Python Wiki
- collections.deque — Python documentation
- Algorithms, 4th edition, §1.3 Bags, Queues, and Stacks (linked lists) — R. Sedgewick and K. Wayne, Princeton University