When using queues in different programming languages, usually there exists a “peek” function which allows us to view the element at the beginning of a queue.

In Python, we can implement a queue data structure using the collections module or the queue module. Unfortunately, neither of these modules have a “peek” function.

If you want to look at the first element of a queue in Python, you can implement your own peek functions which will get the first element of a queue.

Creating deque Peek Function in Python

If you are using the collections module to implement a queue using deque(), we can access the first element to peek at the first element just like you’d access the first item of a list.

Below is an example of how to peek at the first element of a queue when using a deque object in Python.

from collections import deque

q = deque()

q.append(1)
q.append(2)
q.append(3)

print(q[0])  #Peek at the first element

#Output:
1

Creating Queue Peek Function in Python

If you are using the queue module to implement a queue using Queue(), we can access the first element of the “queue” attribute to peek at the first element just like you’d access the first item of a list.

Below is an example of how to peek at the first element of a queue when using a Queue object in Python.

from queue import Queue

q = Queue() 

q.put(1)
q.put(2)

print(q.queue[0])  #Peek at the first element

#Output:
1

Hopefully this article has been useful for you to learn how to create a deque peek function in your Python program.

Categorized in:

Python,

Last Update: February 26, 2024