Get the First element of a Queue in Python

avatar

Borislav Hadzhiev

Last updated: Jun 16, 2022

banner

Photo from Unsplash

Get the First element of a Queue in Python #

Use the get() method to get the first element of a queue in Python. The get() method removes and returns an item from the queue. If you don't want to remove the element, use the queue attribute on the queue and access the element at index 0.

main.py
import queue q = queue.Queue() for item in range(15): q.put(item) print(q.queue[0]) # 👉️ 0 get first without removing it # 👇️ remove and return an item from the queue print(q.get()) # 👉️ 0 (get first) print(q.get()) # 👉️ 1 (get second) print(q.get()) # 👉️ 2 (get third)

If you use deque objects from the collections module, scroll down to the next code snippet.

The queue attribute gives us access to a deque object and deque objects support popleft() operations and indexing.

If you don't want to remove the specific element of the queue and only want to access it, use q.queue[0].

The queue.get method removes and returns an item from the queue.

If you use the collections.deque class, you can access the first element in the queue by accessing the deque object at index 0.

main.py
from collections import deque deq = deque(['a', 'b', 'c']) print(deq[0]) # 👉️ get first print(deq[1]) # 👉️ get second print(deq[2]) # 👉️ get third first = deq.popleft() print(first) # 👉️ 'a' print(deq) # 👉️ deque(['b', 'c'])
Deque objects support indexing, so getting the first element of the queue is the same as getting the first element of a list.

Deque objects also support the popleft() method.

The method removes and returns an element from the left side of the deque.

If no elements are present in the deque, the method raises an IndexError.

If you need to remove and return an element from the right side of the deque, use the pop() method.

main.py
from collections import deque deq = deque(['a', 'b', 'c']) print(deq[0]) # 👉️ get first first = deq.popleft() print(first) # 👉️ 'a' print(deq) # 👉️ deque(['b', 'c']) last = deq.pop() print(last) # 👉️ 'c' print(deq) # 👉️ deque(['b'])
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.