How to get the first and last elements of Deque in Python?
Last Updated :
01 Oct, 2020
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'])
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...