Open In App

How to get the first and last elements of Deque in Python?

Improve
Improve
Like Article
Like
Save
Share
Report

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




# importing the module
from collections import deque  
        
# creating a deque  
dq = deque(['Geeks','for','Geeks', 'is', 'good'])   
  
# displaying the deque
print(dq)
  
# fetching the first element
print(dq[0])
  
# fetching the last element
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




# importing the module
from collections import deque  
        
# creating a deque  
dq = deque(['Geeks','for','Geeks', 'is', 'good'])   
  
# displaying the deque
print(dq)
  
# fetching and deleting the first element
print(dq.popleft())
  
# fetching and deleting the last element
print(dq.pop())
  
# displaying the deque
print(dq)


Output:

deque(['Geeks', 'for', 'Geeks', 'is', 'good'])
Geeks
good
deque(['for', 'Geeks', 'is'])


Last Updated : 01 Oct, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads