I want to check a condition against the front of a queue before deciding whether or not to pop. How can I achieve this in python with collections.deque?
list(my_deque)[0]
seems ugly and poor for performance.
TL;DR: assuming your deque
is called d
, just inspect d[-1]
, since the "rightmost" element in a deque is the front (you might want to test before the length of the deque to make sure it's not empty). Taking @asongtoruin's suggestion, use if d:
to test whether the deque is empty (it's equivalent to if len(d) == 0:
, but more pythonic)
Because deque
s are indexable and you're testing the front. While a deque
has an interface similar to a list, the implementation is optimized for front- and back- operations. Quoting the documentation:
Deques support thread-safe, memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction.
Though list objects support similar operations, they are optimized for fast fixed-length operations and incur O(n) memory movement costs for pop(0) and insert(0, v) operations which change both the size and position of the underlying data representation.
Converting to list might be desirable if you have lots of operations accessing the "middle" of the queue. Again quoting the documentation:
Indexed access is O(1) at both ends but slows to O(n) in the middle. For fast random access, use lists instead.
Conversion to list
is O(n), but every subsequent access is O(1).