[Doc-SIG] queues and stacks for tutorial
Ka-Ping Yee
ping@lfw.org
Fri, 17 Mar 2000 11:28:38 -0600 (CST)
Would this help?
Here's a shot at a couple more sections for chapter 5
of the tutorial, where lists are introduced.
Section 5.1, "More on Lists", introduces the list methods.
It would be nice to put these methods in alphabetical order;
or, perhaps a more logical order would be
append # adding things
insert
extend
remove # removing things
pop
index # finding things
count
reverse # reordering
sort
I recommend putting "append" first in any case because
it is used so much more often than "insert". The
description should be changed to not forward-reference
"insert":
append(x)
Append an item to the list;
a.append(x) is equivalent to a[len(a):] = [x].
We need new entries for "extend" and "pop":
extend(l)
Extend the list by appending all the items in
the given list; equivalent to a[len(a):] = l.
pop(i)
Remove the item at the given position in the list,
and return it. If no index is specified, a.pop()
pops the last item in the list.
Move 5.1.1 to 5.1.3, and add:
5.1.1 Using Lists as Stacks
The list methods make it very easy to use a list as a
stack, where the last element added is the first element
retrieved ("last-in, first-out"). To add an item to
the top of the stack, use append(item). To retrieve an item
from the top of the stack, use pop(). For example:
>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]
5.1.2 Using Lists as Queues
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 append(item). To retrieve an item from
the front of the queue, use pop(0). For example:
>>> queue = ["Eric", "John", "Michael"]
>>> queue.append("Terry") # Terry arrives
>>> queue.append("Graham") # Graham arrives
>>> queue.pop(0)
'Eric'
>>> queue.pop(0)
'John'
>>> queue
['Michael', 'Terry', 'Graham']
-- ?!ng