Python - Queue


lists are not efficient when implementing a queue (FIFO logic). While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one).

To implement a queue , use <wrap box>collections.deque</note> which was designed to have fast appends and pops from both ends.


from collections import deque
queue = deque(["Eric", "John", "Michael"])
queue.append("Terry")           # Terry arrives
queue.append("Graham")          # Graham arrives
queue.popleft()                 # The first to arrive now leaves
queue.popleft()                 # The second to arrive now leaves
queue                           # Remaining queue in order of arrival
deque(['Michael', 'Terry', 'Graham'])

Documentation / Reference

Powered by ComboStrap