Skip to content

Commit 8f8db14

Browse files
committed
Merged revisions 79522 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk ........ r79522 | ezio.melotti | 2010-03-31 10:26:24 +0300 (Wed, 31 Mar 2010) | 1 line Revert r79179 and merge r75584 to explain how to implement a queue using collection.deque instead of a list. ........
1 parent 49c284c commit 8f8db14

1 file changed

Lines changed: 13 additions & 14 deletions

File tree

Doc/tutorial/datastructures.rst

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -137,26 +137,25 @@ Using Lists as Queues
137137

138138
.. sectionauthor:: Ka-Ping Yee <ping@lfw.org>
139139

140+
It is also possible to use a list as a queue, where the first element added is
141+
the first element retrieved ("first-in, first-out"); however, lists are not
142+
efficient for this purpose. While appends and pops from the end of list are
143+
fast, doing inserts or pops from the beginning of a list is slow (because all
144+
of the other elements have to be shifted by one).
140145

141-
You can also use a list conveniently as a queue, where the first element added
142-
is the first element retrieved ("first-in, first-out"). To add an item to the
143-
back of the queue, use :meth:`append`. To retrieve an item from the front of
144-
the queue, use :meth:`pop` with ``0`` as the index. For example::
146+
To implement a queue, use :class:`collections.deque` which was designed to
147+
have fast appends and pops from both ends. For example::
145148

146-
>>> queue = ["Eric", "John", "Michael"]
149+
>>> from collections import deque
150+
>>> queue = deque(["Eric", "John", "Michael"])
147151
>>> queue.append("Terry") # Terry arrives
148152
>>> queue.append("Graham") # Graham arrives
149-
>>> queue.pop(0)
153+
>>> queue.popleft() # The first to arrive now leaves
150154
'Eric'
151-
>>> queue.pop(0)
155+
>>> queue.popleft() # The second to arrive now leaves
152156
'John'
153-
>>> queue
154-
['Michael', 'Terry', 'Graham']
155-
156-
However, since lists are implemented as an array of elements, they are not the
157-
optimal data structure to use as a queue (the ``pop(0)`` needs to move all
158-
following elements). See :ref:`tut-list-tools` for a look at
159-
:class:`collections.deque`, which is designed to work efficiently as a queue.
157+
>>> queue # Remaining queue in order of arrival
158+
deque(['Michael', 'Terry', 'Graham'])
160159

161160

162161
.. _tut-listcomps:

0 commit comments

Comments
 (0)