collections.deque · Python
append
Adds an element at the right end (the back of a queue, the top of a stack).
deque.append(x, /)
Complexity
| Best case | O(1) |
|---|---|
| Worst case | O(1) |
| Extra space | O(1) |
Writes into the rightmost block, allocating a new 64-slot block when it is full. Nothing is ever copied.
Tested example
queue: deque[str] = deque()
queue.append("first") # O(1) at the right end
queue.append("second")
assert list(queue) == ["first", "second"]
recent = deque(maxlen=3) # bounded: old items fall off the other end
for i in range(5):
recent.append(i)
assert list(recent) == [2, 3, 4]
Parameters
- x
- The element.
Behaviour
- Returns
- None.
- Errors and preconditions
- None.
- Changes
- Length grows by 1; with a full maxlen, the leftmost element is discarded.
- Memory and invalidation
- Allocates a block every 64 appends.