logo
Python Data Structures - Interview Questions and Answers
What are deques, and how are they different from lists?
Deques in Python vs. Lists

A deque (double-ended queue) is a specialized data structure from Python's collections module that allows fast O(1) appends and pops from both ends, unlike lists which have O(n) time complexity for operations at the start.


1. What is a Deque?

A deque is an optimized list-like container that allows:
* Fast insertion/removal from both ends (O(1) time complexity).
* Thread-safe (supports locking for multi-threading).
* Efficient memory usage (implemented as a doubly linked list).


2. Creating a Deque

You need to import collections.deque to use it.

from collections import deque

# Creating a deque
dq = deque([1, 2, 3])

# Append elements (to the right)
dq.append(4)  # [1, 2, 3, 4]

# Append elements (to the left)
dq.appendleft(0)  # [0, 1, 2, 3, 4]

print(dq)  # Output: deque([0, 1, 2, 3, 4])

* Faster than list.append() and list.insert(0, x).


3. Deque vs. List – Key Differences
Feature Deque List
Appending at end (.append()) O(1) O(1)
Appending at start (.appendleft()) O(1) O(n)
Popping from end (.pop()) O(1) O(1)
Popping from start (.popleft()) O(1) O(n)
Memory Usage More efficient (linked list) Less efficient for frequent inserts/deletes
Thread-Safe Yes No


4. Deque Operations

a) Removing Elements
dq.pop()  # Removes from right
dq.popleft()  # Removes from left
b) Rotating a Deque
dq.rotate(2)  # Moves last two elements to front
print(dq)

* Useful for circular buffers!

c) Limiting Deque Size (Fixed-Length Queues)
dq = deque(maxlen=3)  # Fixed size of 3
dq.extend([1, 2, 3])
dq.append(4)  # Removes 1 automatically
print(dq)  # Output: deque([2, 3, 4], maxlen=3)

* Great for implementing caches and sliding windows!


5. When to Use Deques Instead of Lists?

* Fast insert/remove at both ends (e.g., queues, caching).
* Efficiently handle large datasets (e.g., log files, sliding windows).
* Ideal for FIFO (first-in, first-out) and LIFO (last-in, first-out) structures.