CKTIS / Python
Remove the leftmost item with deque.popleft()
`popleft()` removes and returns the first item in a deque. In a sliding window, it lets you discard indices that fall before the window’s left boundary.
Version: Python 3.12
Syntax
removed = d.popleft()collections.deque.popleft is an instance method of deque. The call d.popleft() takes no arguments: it removes the leftmost item from d and returns it. An empty deque raises IndexError. By contrast, d[0] only reads the first item, while d.pop() removes and returns the rightmost item.
Removing one item from the left takes approximately O(1) time. By comparison, list.pop(0) takes O(n) because the remaining list items must shift.
If the deque stores indices in increasing order, discard the first index while d[0] < left, where left is the inclusive left boundary of the sliding window. The guard while d and d[0] < left skips the lookup if the deque is empty. An index equal to left stays in the window. If another thread can modify d, checking and then removing are not a single atomic operation.
Examples
from collections import deque
d = deque([0, 2, 3, 5])
left = 3
while d and d[0] < left:
removed = d.popleft()
print(removed)
print(list(d))Result
0 2 [3, 5]
With `left = 3`, the loop prints the removed indices `0` and `2` in order, followed by the remaining contents: `[3, 5]`.
Related lessons
- Python · Lesson 41 · Advanced · Version: 5