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.
The deque data structure from the collections module does not have a peek method, but similar results can be achieved by fetching the elements with square brackets. The first element can be accessed using [0] and the last element can be accessed using [-1].
front() is used to reference the first element of the deque container. This function can be used to fetch the first element of a deque. This is an inbuilt function from C++ Standard Template Library(STL).
A peek function in the python queue is used to print the first element of the queue. It returns the item which is present at the front index of the queue. It will not remove the first element but print it. Let us construct a function inside the class queue to perform a peek operation.
To directly answer your question, you index a deque with an iterable of indices the same as you do a list - [test[i] for i in idx] . But deque random lookup is O(n) (which could matter more for larger deques), and if you want to do NumPy-style indexing into the deque you won't be able to.
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 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).
You can simply find the last element using my_deque[-1]
or my_deque[len(my_deque)-1]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With