A data structure is a way of organising information so that certain operations are easy and fast. You already know lists, dictionaries and sets; now we will see structures that are defined by how you get in and out of them.
The stack: last in, first out
A stack works like a pile of plates: you only add or remove from the top. It is called LIFO (*last in, first out*). A Python list already works as a stack: append pushes and pop() pops, both very fast.
stack = []
stack.append("a")
stack.append("b")
stack.append("c")
print(stack.pop()) # c (the last one in)
print(stack.pop()) # b
print(stack) # ['a']
print(stack[-1]) # a (peek at the top without removing it)
Careful: pop() on an empty stack raises IndexError. Check first with if stack:.
Where stacks are used
- Undo in an editor: every action is pushed.
- The browser back button, as in Browser history.
- Matching symbols: the last opened bracket is the first one that must be closed, as in Balanced brackets.
- Evaluating postfix expressions, as in Postfix calculator.
- Recursion itself: every call is pushed onto the "call stack".
def balanced(text):
closers = {")": "(", "]": "["}
stack = []
for c in text:
if c in "([":
stack.append(c)
elif c in closers:
if not stack or stack.pop() != closers[c]:
return False
return not stack
print(balanced("(a[b])")) # True
print(balanced("(a[b)]")) # False
The queue: first in, first out
A queue works like a line in a shop: you join at the back and leave from the front. It is FIFO (*first in, first out*). With a list, removing the first element (list.pop(0)) is slow, because all the others have to be shifted. That is what collections.deque is for.
from collections import deque
queue = deque()
queue.append("Ana") # joins at the back
queue.append("Luis")
queue.append("Eva")
print(queue.popleft()) # Ana (leaves from the front)
print(queue) # deque(['Luis', 'Eva'])
deque: a double-ended queue
deque (*double-ended queue*) adds and removes quickly at both ends: append, appendleft, pop and popleft. It can also rotate with rotate and limit its size with maxlen.
from collections import deque
d = deque([1, 2, 3, 4, 5])
d.rotate(2)
print(d) # deque([4, 5, 1, 2, 3])
d.rotate(-1)
print(d) # deque([5, 1, 2, 3, 4])
last = deque(maxlen=3)
for n in range(1, 7):
last.append(n)
print(last) # deque([4, 5, 6], maxlen=3)
A deque with maxlen is perfect for keeping "the last N elements". With rotate you can solve The Josephus problem in a few lines.
Summary
| Structure | Enters at | Leaves from | In Python |
|---|---|---|---|
| Stack (LIFO) | one end | the same end | list with append / pop() |
| Queue (FIFO) | back | front | deque with append / popleft() |
| Double-ended queue | both | both | deque |