Python - Queue

Card Puncher Data Processing

About

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

collections.deque

which was designed to have fast appends and pops from both ends.

Example

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
'Eric'

queue.popleft()                 # The second to arrive now leaves
'John'

queue                           # Remaining queue in order of arrival
deque(['Michael', 'Terry', 'Graham'])

Documentation / Reference







Share this page:
Follow us:
Task Runner