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

A deque (double-ended queue) is a data structure from Python's collections module that allows efficient insertion and deletion from both ends. Unlike traditional queues that follow FIFO (First In First Out), deques provide flexible access to elements at either end.

In this article, we will explore two approaches to get the first and last elements of a deque in Python.

Using popleft() and pop() Functions

The popleft() function removes and returns the first element, while pop() removes and returns the last element from the deque.

Syntax

first_element = deque_name.popleft()
last_element = deque_name.pop()

Important: These functions modify the original deque by removing the elements.

Example

from collections import deque

fruits = deque(['Apple', 'Mango', 'Grapes', 'Banana', 'Watermelon'])
print("Original deque:", fruits)

first_element = fruits.popleft()
last_element = fruits.pop()

print("First element:", first_element)
print("Last element:", last_element)
print("Deque after removal:", fruits)
Original deque: deque(['Apple', 'Mango', 'Grapes', 'Banana', 'Watermelon'])
First element: Apple
Last element: Watermelon
Deque after removal: deque(['Mango', 'Grapes', 'Banana'])

Using Index Access

You can access the first and last elements without removing them using index [0] for the first element and [-1] for the last element.

Syntax

first_element = deque_name[0]
last_element = deque_name[-1]

This approach preserves the original deque structure.

Example

from collections import deque

numbers = deque([23, 12, 45, 67, 32])
print("Original deque:", numbers)

first_element = numbers[0]
last_element = numbers[-1]

print("First element:", first_element)
print("Last element:", last_element)
print("Deque unchanged:", numbers)
Original deque: deque([23, 12, 45, 67, 32])
First element: 23
Last element: 32
Deque unchanged: deque([23, 12, 45, 67, 32])

Comparison

Method Modifies Deque? Time Complexity Best For
popleft() / pop() Yes (removes elements) O(1) When you need to consume elements
Index access [0] / [-1] No O(1) When you need to peek at elements

Handling Empty Deques

Both approaches will raise an IndexError if the deque is empty ?

from collections import deque

empty_deque = deque()

# Safe way to check before accessing
if empty_deque:
    print("First:", empty_deque[0])
    print("Last:", empty_deque[-1])
else:
    print("Deque is empty!")
Deque is empty!

Conclusion

Use index access [0] and [-1] when you need to peek at elements without modifying the deque. Use popleft() and pop() when you need to consume and remove elements from the deque.

Updated on: 2026-03-27T09:33:16+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements