Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit de414a2

Browse files
committed
Merged revisions 79525 via svnmerge from
svn+ssh://[email protected]/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://[email protected]/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 0d8a1dd commit de414a2

1 file changed

Lines changed: 13 additions & 9 deletions

File tree

Doc/tutorial/datastructures.rst

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

138138
.. sectionauthor:: Ka-Ping Yee <[email protected]>
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']
157+
>>> queue # Remaining queue in order of arrival
158+
deque(['Michael', 'Terry', 'Graham'])
155159

156160

157161
.. _tut-listcomps:

0 commit comments

Comments
 (0)