Monday, October 6, 2025
HomeLanguagesHow to get the first and last elements of Deque in Python?

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

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'])
RELATED ARTICLES

Most Popular

Dominic
32338 POSTS0 COMMENTS
Milvus
86 POSTS0 COMMENTS
Nango Kala
6707 POSTS0 COMMENTS
Nicole Veronica
11871 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11936 POSTS0 COMMENTS
Shaida Kate Naidoo
6825 POSTS0 COMMENTS
Ted Musemwa
7089 POSTS0 COMMENTS
Thapelo Manthata
6779 POSTS0 COMMENTS
Umr Jansen
6781 POSTS0 COMMENTS