summaryrefslogtreecommitdiffstats
path: root/Doc/tutorial
diff options
context:
space:
mode:
authorEzio Melotti <ezio.melotti@gmail.com>2010-03-31 07:48:01 (GMT)
committerEzio Melotti <ezio.melotti@gmail.com>2010-03-31 07:48:01 (GMT)
commitde414a2e9108058e0cccde512f42b5d2d251536f (patch)
tree8198e9dc55ef04311a5b58ca5ffb04babf4df78a /Doc/tutorial
parent0d8a1dd64707ad7459871f7d6035a6dd9b3cd123 (diff)
downloadcpython-de414a2e9108058e0cccde512f42b5d2d251536f.zip
cpython-de414a2e9108058e0cccde512f42b5d2d251536f.tar.gz
cpython-de414a2e9108058e0cccde512f42b5d2d251536f.tar.bz2
Merged revisions 79525 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/branches/py3k ................ r79525 | ezio.melotti | 2010-03-31 10:45:32 +0300 (Wed, 31 Mar 2010) | 9 lines 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. ........ ................
Diffstat (limited to 'Doc/tutorial')
-rw-r--r--Doc/tutorial/datastructures.rst22
1 files changed, 13 insertions, 9 deletions
diff --git a/Doc/tutorial/datastructures.rst b/Doc/tutorial/datastructures.rst
index ef364b2..b562558 100644
--- a/Doc/tutorial/datastructures.rst
+++ b/Doc/tutorial/datastructures.rst
@@ -137,21 +137,25 @@ Using Lists as Queues
.. sectionauthor:: Ka-Ping Yee <ping@lfw.org>
+It is also possible to use a list as a queue, where the first element added is
+the first element retrieved ("first-in, first-out"); however, lists are not
+efficient for this purpose. 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).
-You can also use a list conveniently as a queue, where the first element added
-is the first element retrieved ("first-in, first-out"). To add an item to the
-back of the queue, use :meth:`append`. To retrieve an item from the front of
-the queue, use :meth:`pop` with ``0`` as the index. For example::
+To implement a queue, use :class:`collections.deque` which was designed to
+have fast appends and pops from both ends. For example::
- >>> queue = ["Eric", "John", "Michael"]
+ >>> from collections import deque
+ >>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Terry") # Terry arrives
>>> queue.append("Graham") # Graham arrives
- >>> queue.pop(0)
+ >>> queue.popleft() # The first to arrive now leaves
'Eric'
- >>> queue.pop(0)
+ >>> queue.popleft() # The second to arrive now leaves
'John'
- >>> queue
- ['Michael', 'Terry', 'Graham']
+ >>> queue # Remaining queue in order of arrival
+ deque(['Michael', 'Terry', 'Graham'])
.. _tut-listcomps: