Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the first value of a deque without deleting it?

Tags:

python

deque

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?

like image 531
maynull Avatar asked Sep 21 '17 00:09

maynull


1 Answers

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.

like image 88
wim Avatar answered Oct 18 '22 02:10

wim