typestar

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

  1. Backs the stack with a plain list.
  2. push appends to the end.
  3. pop removes the last item, raising IndexError when empty.

Keywords and builtins used here

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.

Type this snippet

Step 5 of 5 in Classes, step 43 of 72 in Language basics.

← Previous Next →