Queue in Python - Part 1
Wed Nov 02, 2016 · 111 words

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"])
# output is: deque(['c', 'd', 'e'])

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

back · he thought · he could · so he did · main