Stacks (LIFO) / Queues (FIFO)
With a queue, you remove the item least recently added (first-in, first-out or FIFO); but with a stack, you remove the item most recently added (last-in, first-out or LIFO).
Stacks (LIFO)
`collections.deque` – Fast & Robust Stacks
Queues (FIFO)
list
is backed by a dynamic array which makes it great for fast random access, but requires occasional resizing when elements are added or removed. The list over-allocates its backing storage so that not every push or pop requires resizing, and you get an amortized O(1) time complexity for these operations. But you do need to be careful to only insert and remove items “from the right side” using append()
and pop()
. Otherwise, performance slows down to O(n).
collections.deque
is backed by a doubly-linked list which optimizes appends and deletes at both ends and provides consistent O(1) performance for these operations. Not only is its performance more stable, the deque
class is also easier to use because you don’t have to worry about adding or removing items from “the wrong end.”
Last updated