Repaso
EspaƱol
PythonIntermediatePY-33

Which structure gives O(1) append and pop at both ends?

Options

  1. list
  2. collections.deque (Correct option)
  3. tuple
  4. heapq

Answer

collections.deque

Why

A Python list is an array: inserting or removing at the FRONT shifts every other element, which is O(n).

collections.deque (double-ended queue) is built for fast adds and removes at both ends: O(1).

Use it for queues (first in, first out) and sliding windows.

Remember

Need a queue in Python? Use collections.deque.

Key terms

Practice this question in Repaso