Deque is a Double Ended Queue which is implemented using the collections module in Python. Let us see how can we get the first and the last value in a Deque.
Method 1: Accessing the elements by their index.
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].
Python3
from collections import deque
dq = deque([ 'Geeks' , 'for' , 'Geeks' , 'is' , 'good' ])
print (dq)
print (dq[ 0 ])
print (dq[ - 1 ])
|
Output:
deque(['Geeks', 'for', 'Geeks', 'is', 'good'])
Geeks
good
Method 2: Using the popleft() and pop() method
popleft() method is used to pop the first element or the element from the left side of the queue and the pop() method to pop the last element or the element form the right side of the queue. It should be noted that these methods also delete the elements from the deque, so they should not be preferred when only fetching the first and the last element is the objective.
Python3
from collections import deque
dq = deque([ 'Geeks' , 'for' , 'Geeks' , 'is' , 'good' ])
print (dq)
print (dq.popleft())
print (dq.pop())
print (dq)
|
Output:
deque(['Geeks', 'for', 'Geeks', 'is', 'good'])
Geeks
good
deque(['for', 'Geeks', 'is'])
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
01 Oct, 2020
Like Article
Save Article