
Next, we consider a completely different way to implement a stack, using a fundamental data structure known as a linked list. The primary characteristics of this implementation are that it uses space linear in the number of items in the stack and that the the push and pop operations take constant amortized time.

The diagram at right is a trace for the test file tobe.txt. The test client in arraystack.py allows for testing with an arbitrary sequence of operations: it does a push() for each string on standard input except the string consisting of a minus sign, for which it does a pop().

This policy is known as first-in-first-out or FIFO.

But when we remove an item, which one do we choose? The rule used for a queue is to always remove the item that has been in the collection the most amount of time. When we insert an item, our intent is clear. Each is defined by two basic operations: insert a new item, and remove an item. However, like lists, a deque can be used for other purposes too.In this section, we introduce two closely-related data types for manipulating arbitrarily large collections of objects: the stack and the queue. You could also use the que() type it is usually slightly faster than a list for the typical patterns seen when using either as a stack. Just limit any use to list.append() and list.pop() (the latter with no arguments) to treat a list as a stack. The Python standard library doesn't come with a specific stack datatype a list object does just fine. Hardly a list in sight (somewhat artificially), but it is definitely a stack: > stack = Stack() Raise ValueError("Can't pop from an empty stack")

You could implement a stack with a custom class: from collections import namedtupleĬlass _Entry(namedtuple('_Entry', 'value next')): You wouldn't try that with a stack of beer crates with someone on top! Lists on the other hand are far more versatile, you can add and remove elements anywhere in the list. Stacks are just things you add stuff to, and when you take stuff away from a stack again, you do so in reverse order, first in, last out style. That's why that section of the tutorial is named Using Lists as Stacks. The documentation uses a Python list object to implement one.
