How to peek front of deque without popping?

TL;DR: assuming your deque is called d, just inspect d[0], since the “leftmost” 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)

###Why not converting to list?
Because deques 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).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)