diff options
| author | Raymond Hettinger <python@rcn.com> | 2009-10-21 17:44:38 (GMT) |
|---|---|---|
| committer | Raymond Hettinger <python@rcn.com> | 2009-10-21 17:44:38 (GMT) |
| commit | f04545565a96ef5ba8d67045b2813ba60ae9a0b0 (patch) | |
| tree | c75e98aacbbd7408a1babbc72637d7ab22520484 | |
| parent | 3f902a0e6575c64fe3d09cbd686787b714ffa563 (diff) | |
| download | cpython-f04545565a96ef5ba8d67045b2813ba60ae9a0b0.zip cpython-f04545565a96ef5ba8d67045b2813ba60ae9a0b0.tar.gz cpython-f04545565a96ef5ba8d67045b2813ba60ae9a0b0.tar.bz2 | |
Update advice on how to implement a queue.
| -rw-r--r-- | Doc/tutorial/datastructures.rst | 22 |
1 files changed, 13 insertions, 9 deletions
diff --git a/Doc/tutorial/datastructures.rst b/Doc/tutorial/datastructures.rst index a56fd2b..dfc2b33 100644 --- a/Doc/tutorial/datastructures.rst +++ b/Doc/tutorial/datastructures.rst @@ -138,21 +138,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-functional: |
