[Python-checkins] r75584 - python/branches/release26-maint/Doc/tutorial/datastructures.rst

raymond.hettinger python-checkins at python.org
Wed Oct 21 19:44:38 CEST 2009


Author: raymond.hettinger
Date: Wed Oct 21 19:44:38 2009
New Revision: 75584

Log:
Update advice on how to implement a queue.

Modified:
   python/branches/release26-maint/Doc/tutorial/datastructures.rst

Modified: python/branches/release26-maint/Doc/tutorial/datastructures.rst
==============================================================================
--- python/branches/release26-maint/Doc/tutorial/datastructures.rst	(original)
+++ python/branches/release26-maint/Doc/tutorial/datastructures.rst	Wed Oct 21 19:44:38 2009
@@ -138,21 +138,25 @@
 
 .. sectionauthor:: Ka-Ping Yee <ping at 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-functional:


More information about the Python-checkins mailing list