Stack class in Python
The LIFO structure underneath undo history and parsers.
class Stack:
def __init__(self):
self._items = []
def push(self, item):
self._items.append(item)
def pop(self):
if not self._items:
raise IndexError("pop from empty stack")
return self._items.pop()
How it works
- Backs the stack with a plain list.
pushappends to the end.popremoves the last item, raisingIndexErrorwhen empty.
Keywords and builtins used here
Stackclassdefifpoppushraisereturnself
The run, in numbers
- Lines
- 11
- Characters to type
- 199
- Tokens
- 58
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 35 seconds.
Step 5 of 5 in Classes, step 43 of 72 in Language basics.