collections.deque() / collections.OrderedDict()
| Since: | Python 3.0(2008) |
|---|
collections.deque is a class that provides a double-ended queue, allowing you to add and remove elements from either end in O(1) time. Operations at the front of a regular list take O(n) time, but with deque, front operations also run in O(1). collections.OrderedDict is a dictionary that preserves insertion order. While regular dictionaries in Python 3.7 and later also guarantee insertion order, OrderedDict provides additional features such as order-aware comparisons and move operations.
Syntax
from collections import deque, OrderedDict # Create a deque dq = deque([initial_elements], maxlen=max_length) # Create an OrderedDict od = OrderedDict()
Functions and Methods
| Function / Method | Description |
|---|---|
| deque(iterable) | Creates a double-ended queue. You can specify maxlen to limit the maximum number of elements. |
| dq.append(x) | Adds element x to the right end. |
| dq.appendleft(x) | Adds element x to the left end. |
| dq.pop() | Removes and returns the element at the right end. |
| dq.popleft() | Removes and returns the element at the left end. |
| dq.rotate(n) | Rotates the deque n steps to the right (use a negative value to rotate left). |
| dq.extend(iterable) | Adds multiple elements to the right end. |
| dq.extendleft(iterable) | Adds multiple elements to the left end in reverse order. |
| OrderedDict() | Creates a dictionary that preserves insertion order. |
| od.move_to_end(key) | Moves the specified key to the end (or the beginning) of the dictionary. |
| od.popitem(last=True) | Removes and returns the last item (or the first item if last=False). |
Sample Code
collections_deque.py
from collections import deque, OrderedDict
# Basic deque operations
dq = deque(['Iori Yagami', 'Kusanagi Kyo', 'Terry Bogard'])
dq.append('Blue Mary') # Add to the right
dq.appendleft('Goenitz') # Add to the left
print(dq) # deque(['Goenitz', 'Iori Yagami', 'Kusanagi Kyo', 'Terry Bogard', 'Blue Mary'])
dq.pop() # Remove from the right → 'Blue Mary'
dq.popleft() # Remove from the left → 'Goenitz'
print(dq) # deque(['Iori Yagami', 'Kusanagi Kyo', 'Terry Bogard'])
# rotate: shift elements n steps to the right
dq.rotate(1)
print(dq) # deque(['Terry Bogard', 'Iori Yagami', 'Kusanagi Kyo'])
# With maxlen, elements that overflow are automatically dropped
queue = deque(maxlen=3)
for name in ['Iori Yagami', 'Kusanagi Kyo', 'Terry Bogard', 'Blue Mary', 'Goenitz']:
queue.append(name)
print(queue) # deque(['Terry Bogard', 'Blue Mary', 'Goenitz'], maxlen=3)
# Basic OrderedDict operations
od = OrderedDict()
od['a'] = 1
od['b'] = 2
od['c'] = 3
print(list(od.keys())) # ['a', 'b', 'c']
# Move a key to the end
od.move_to_end('a')
print(list(od.keys())) # ['b', 'c', 'a']
# Move a key to the beginning
od.move_to_end('a', last=False)
print(list(od.keys())) # ['a', 'b', 'c']
# Remove the last item with popitem
key, val = od.popitem(last=True)
print(key, val) # c 3
Running the code produces the following output:
python3 collections_deque.py deque(['Goenitz', 'Iori Yagami', 'Kusanagi Kyo', 'Terry Bogard', 'Blue Mary']) deque(['Iori Yagami', 'Kusanagi Kyo', 'Terry Bogard']) deque(['Terry Bogard', 'Iori Yagami', 'Kusanagi Kyo']) deque(['Terry Bogard', 'Blue Mary', 'Goenitz'], maxlen=3) ['a', 'b', 'c'] ['b', 'c', 'a'] ['a', 'b', 'c'] c 3
Common Mistakes
Common Mistake 1: Index access is slow
Random access to elements in the middle of a 'deque' (e.g., d[5]) runs in O(n) time. If you frequently access elements by index, a list is faster.
from collections import deque queue = deque(['Iori Yagami', 'Kusanagi Kyo', 'Terry Bogard', 'Blue Mary', 'Goenitz']) # deque: O(1) at both ends, O(n) for middle access print(queue[0]) # 'Iori Yagami' — both ends are fine print(queue[-1]) # 'Goenitz' — both ends are fine print(queue[2]) # 'Terry Bogard' — middle access is slower than a list # Use a list when frequent index access is needed as_list = list(queue) print(as_list[2]) # 'Terry Bogard' (O(1))
Common Mistake 2: Elements silently disappear when maxlen is exceeded
When you add elements to a 'deque' with a 'maxlen' set, elements from the opposite end are automatically dropped. This can cause unexpected behavior if you are not aware that data is being discarded.
from collections import deque
# With maxlen=3, adding an element removes the one at the other end
history = deque(maxlen=3)
history.append('Iori enters')
history.append('Kyo enters')
history.append('Terry enters')
print(history) # deque(['Iori enters', 'Kyo enters', 'Terry enters'], maxlen=3)
history.append('Mary enters') # 'Iori enters' is dropped from the left
print(history) # deque(['Kyo enters', 'Terry enters', 'Mary enters'], maxlen=3)
Notes
By setting a maximum length (maxlen), a deque can serve as a fixed-size queue or a sliding window. When you add elements beyond the maximum length, elements are automatically dropped from the opposite end. It is well suited for both queue (FIFO) and stack (LIFO) use cases, and replacing a list with a deque can significantly improve performance for front-end operations.
OrderedDict retains relevance even in Python 3.7 and later, where regular dictionaries already preserve insertion order. It provides features not available in regular dictionaries, such as move_to_end() and order-aware equality comparisons. A common use case is implementing an LRU (Least Recently Used) cache.
If you find any errors or copyright issues, please contact us.