Programming Search⌘K

Featureintro

Using lists as stacks

Also called stack, list as stack, LIFO, last-in first-out, push and pop, append and pop, stack in Python.

A list works as a stack: append() pushes an item on the top and pop() with no index takes the item from the top. The last item added is the first item taken out.

Language
Python

Synopsis

stack = [3, 4, 5]
stack.append(6)
stack.append(7)
print(stack)
print(stack.pop(), stack.pop())
print(stack, stack[-1])
Output
[3, 4, 5, 6, 7]
7 6
[3, 4, 5] 5

The end of the list is the top of the stack. stack[-1] reads the top item and does not remove it.

Semantics

r1. A stack is a structure "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(). To retrieve an item from the top of the stack, use pop() without an explicit index."1

r2. pop() is described so: "Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. It raises an IndexError if the list is empty or the index is outside the list range."1 Example: empty-pop.

r3. The deque documentation says that list objects "are optimized for fast fixed-length operations and incur O(n) memory movement costs for pop(0) and insert(0, v) operations".2 A stack uses only the end of the list, so it does not move the other items.

Examples

def balanced(text):
    pairs = {")": "(", "]": "[", "}": "{"}
    stack = []
    for ch in text:
        if ch in "([{":
            stack.append(ch)
        elif ch in pairs:
            if not stack or stack.pop() != pairs[ch]:
                return False
    return not stack

print(balanced("(a[b]{c})"), balanced("(]"), balanced("(("))
Output
True False False

Each closing bracket must match the last open bracket, so a stack is the right structure (rule r1).

history = []
text = ""
for word in ["one", "two", "three"]:
    history.append(text)
    text += word + " "
print(repr(text))
text = history.pop()
text = history.pop()
print(repr(text))
Output
'one two three '
'one '

Each pop() gives back the state before the last change.

Pitfalls

pop() on an empty list is an error:

This code raises IndexError, on purpose.

stack = []
stack.pop()

Test the list first with if stack: (rule r2).

pop(0) takes the bottom item, not the top item. A loop of pop(0) calls on a long list is slow (rule r3). Use collections.deque for a queue.

Comparison

In Go, a slice can also work as a stack. "The variadic function append appends zero or more values x to a slice s of type S and returns the resulting slice, also of type S."3 To pop, a Go program reads s[len(s)-1] and then sets s = s[:len(s)-1]. A Python list does both steps in one pop() call (rule r2).

References

  1. The Python Tutorial, 5. Data Structures, 5.1. More on Lists; 5.1.1. Using Lists as Stacks
  2. collections, Python 3.15 documentation, deque objects
  3. The Go Programming Language Specification, Appending to and copying slices

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source