Skip to content
Rezha Julio
Go back

Queue in Python - Part 1

1 min read

Best way to implement a simple queue

A simple list can be easily used and implemented as a queue abstract data structure. A queue implies the first-in, first-out principle.

However, this approach will prove inefficient because inserts and pops from the beginning of a list are slow (all elements need shifting by one).

It’s recommended to implement queues using the collections.deque module as it was designed with fast appends and pops from both ends.

from collections import deque
queue = deque(["a", "b", "c"])
queue.append("d")
queue.append("e")
queue.popleft()
print(queue)
# output is: deque(['c', 'd', 'e'])

A reverse queue can be implemented by opting for appendleft instead of append and pop instead of popleft.


Related Posts


Previous Post
Queue in Python - Part 2
Next Post
Fix Java Unsupported major.minor version 52.0 on Ubuntu