I use Python 3.6.1 and I use deque() from collections quite often due to its convenience. This time, I need to get the first value of a deque and wonder if it's possible.
The problem is that I can do that using .popleft()
, but it ends up deleting the value at the same time. I thought of list(deque01)[0]
, but I'm worried whether or not it's so much resource-consuming when deque01 is big or the process of getting the first value is repeated many times. Are there any methods or tricks to do this effectively?
For the deque
data structure, this is usually called a "peek" operation, and in Python it's just implemented with the usual datamodel's __getitem__
dunder.
This example below is taken straight from the docs:
>>> from collections import deque
>>> d = deque('ghi') # make a new deque with three items
>>> d[0] # peek at leftmost item
'g'
>>> d[-1] # peek at rightmost item
'i'
Note that even though the interface looks similar to lists, deques are only giving fast access at the leftmost or rightmost items. It's slower to access data in the middle, as opposed to a list, where it's fast to index it anywhere.