@@ -138,26 +138,25 @@ Using Lists as Queues
138138
139139..
sectionauthor ::
Ka-Ping Yee <[email protected] > 140140
141+ It is also possible to use a list as a queue, where the first element added is
142+ the first element retrieved ("first-in, first-out"); however, lists are not
143+ efficient for this purpose. While appends and pops from the end of list are
144+ fast, doing inserts or pops from the beginning of a list is slow (because all
145+ of the other elements have to be shifted by one).
141146
142- You can also use a list conveniently as a queue, where the first element added
143- is the first element retrieved ("first-in, first-out"). To add an item to the
144- back of the queue, use :meth: `append `. To retrieve an item from the front of
145- the queue, use :meth: `pop ` with ``0 `` as the index. For example::
147+ To implement a queue, use :class: `collections.deque ` which was designed to
148+ have fast appends and pops from both ends. For example::
146149
147- >>> queue = ["Eric", "John", "Michael"]
150+ >>> from collections import deque
151+ >>> queue = deque(["Eric", "John", "Michael"])
148152 >>> queue.append("Terry") # Terry arrives
149153 >>> queue.append("Graham") # Graham arrives
150- >>> queue.pop(0)
154+ >>> queue.popleft() # The first to arrive now leaves
151155 'Eric'
152- >>> queue.pop(0)
156+ >>> queue.popleft() # The second to arrive now leaves
153157 'John'
154- >>> queue
155- ['Michael', 'Terry', 'Graham']
156-
157- However, since lists are implemented as an array of elements, they are not the
158- optimal data structure to use as a queue (the ``pop(0) `` needs to move all
159- following elements). See :ref: `tut-list-tools ` for a look at
160- :class: `collections.deque `, which is designed to work efficiently as a queue.
158+ >>> queue # Remaining queue in order of arrival
159+ deque(['Michael', 'Terry', 'Graham'])
161160
162161
163162.. _tut-functional :
0 commit comments