Start learning free

LESSON 65 OF 69 · PROJECTS: OBJECT-ORIENTED

Stack Implementation in Python: Build a MyStack Class

Practice Read the full explanation

A stack is a pile where you only touch the top: the last value you put in is the first one you take out (LIFO, last in, first out), like a pile of plates. Build a class MyStack that stores whole numbers in a Python list kept in self._data, created in the constructor __init__(self) and offers four operations.

The methods:

  • def push(self, value)
  • def pop(self)
  • def peek(self)
  • def size(self)

Rules:

  • push puts the value on top of the stack. It returns nothing.
  • pop removes the top value (the one pushed last) and returns it.
  • peek returns the top value but leaves it on the stack, so the size does not change.
  • size returns how many values are on the stack. A new stack has size 0, and after popping everything the size is 0 again.
  • The stack keeps working after it becomes empty: you can push again.
  • Calling pop or peek on an empty stack is not part of this exercise and the tests never do it. (In Python, pop() on an empty list raises an IndexError.)

You start with: The starter already contains the code that uses your stack (below).

s = MyStack()
s.push(10)
s.push(20)
s.push(30)
print("Top: " + str(s.peek()))
print("Size: " + str(s.size()))
print("Pop: " + str(s.pop()))
print("Size: " + str(s.size()))
print("Pop: " + str(s.pop()))
print("Pop: " + str(s.pop()))
print("Empty size: " + str(s.size()))
s.push(7)
print("Top: " + str(s.peek()))
print("Size: " + str(s.size()))

Expected output:

Top: 30
Size: 3
Pop: 30
Size: 2
Pop: 20
Pop: 10
Empty size: 0
Top: 7
Size: 1

Reading the output: after pushing 10, 20 and 30 the top is 30 and the size 3. Popping gives 30, leaving size 2. Two more pops give 20 and then 10 (last in, first out), the stack is empty (size 0), and after pushing 7 the top is 7 and the size 1.


The top of the stack is the end of the list: adding and removing at the end is fast, and the last value pushed is always the last element.

Python lists already have append and pop(), and [-1] is the last element. A leading underscore (_data) marks the list as internal to the class.

class MyStack:
    def __init__(self):
        self._data = []

    def push(self, value):
        self._data.append(value)

    def pop(self):
        return self._data.pop()

    def peek(self):
        return self._data[-1]

    def size(self):
        return len(self._data)

STEP 1 OF 11
    Ctrl + Enter to check

    PYTHON · PROJECTS: OBJECT-ORIENTED

    Stack Impl in Python, explained

    Problem overview

    A stack is a pile where you only touch the top. The last value you put in is the first one you take out, which is called LIFO, last in, first out, like a pile of plates. You build a class MyStack that keeps whole numbers in a Python list, self._data, and offers four methods:

    • push(self, value) puts a value on top and returns nothing.
    • pop(self) removes the top value and returns it.
    • peek(self) returns the top value and leaves it on the stack.
    • size(self) returns how many values are on the stack.

    The driver pushes 10, 20 and 30, looks at the top (30), reads the size (3), pops 30, pops 20 and 10, shows that the size is 0, pushes 7 and checks the top and size again.

    Approach: the end of the list is the top

    A Python list is already a good stack, as long as you work at one end. Appending to the end and removing from the end are cheap, and the last element is always the value pushed most recently. So the top of the stack is the end of the list. Working at the start of the list instead would force every other element to shift.

    Each method then wraps a single list operation: append for push, the list's own pop() for pop, index -1 for peek and len for size. The class adds a clear vocabulary on top of the list and a leading underscore in _data that says "internal, use the methods". The underscore is a convention, and Python doesn't enforce it.

    Every stack gets its own list, because self._data = [] runs inside __init__ each time a stack is created. Two stacks never share their contents.

    Step by step

    1. Declare the class MyStack. A class body can't be empty, so the next step gives it a line.
    2. Add the constructor, __init__(self). It runs once, when the driver writes MyStack().
    3. Create the storage: an empty list in self._data. A new stack holds nothing, so its size is 0.
    4. Add push(self, value), at the same indentation as __init__.
    5. Append value to the end of self._data. The end is the top.
    6. Add pop(self), which takes only self.
    7. Return the list's own pop(). That single call removes the last item and hands it back, which is exactly what a stack's pop promises.
    8. Add peek(self), a method that looks without taking.
    9. Return self._data[-1]. The index -1 means the last item, and reading by index removes nothing.
    10. Add size(self).
    11. Return len(self._data). One value per list item, so the length is the size.

    The solution in Python

    class MyStack:
        def __init__(self):
            self._data = []
    
        def push(self, value):
            self._data.append(value)
    
        def pop(self):
            return self._data.pop()
    
        def peek(self):
            return self._data[-1]
    
        def size(self):
            return len(self._data)
    
    s = MyStack()
    s.push(10)
    s.push(20)
    s.push(30)
    print("Top: " + str(s.peek()))
    print("Size: " + str(s.size()))
    print("Pop: " + str(s.pop()))
    print("Size: " + str(s.size()))
    print("Pop: " + str(s.pop()))
    print("Pop: " + str(s.pop()))
    print("Empty size: " + str(s.size()))
    s.push(7)
    print("Top: " + str(s.peek()))
    print("Size: " + str(s.size()))
    

    Two methods share a name with a list method, but they are different things. MyStack.pop is the method you wrote. Inside it, self._data.pop() calls the list's method, so there is no clash.

    What the driver prints

    Top: 30
    Size: 3
    Pop: 30
    Size: 2
    Pop: 20
    Pop: 10
    Empty size: 0
    Top: 7
    Size: 1
    

    Pushing 10, 20, 30 puts 30 on top. peek reports it without removing anything, so the size stays 3. Each pop then returns the newest remaining value: 30, 20, 10. When the stack is empty, size() is 0, and the stack still works: after push(7) the top is 7 and the size is 1.

    Complexity

    Every method is O(1). Appending to a list is amortized constant time (an occasional append has to grow the list's storage, but averaged over many pushes the cost per push stays constant). Removing the last item, reading [-1] and calling len don't depend on how many values the stack holds. The stack uses O(n) space for n values.

    Edge cases and common mistakes

    • An empty stack. The lesson's tests never call pop or peek on an empty stack. With this solution, pop() raises IndexError: pop from empty list and peek() raises IndexError: list index out of range.
    • Reusing a stack after it empties. Nothing special is needed: pushing again simply starts filling the list again.
    • peek that removes. Using self._data.pop() in peek would return the right value but shrink the stack. After two peek calls on a stack holding 1 and 2, the size must still be 2.
    • Working at the front. insert(0, value) and pop(0) also give LIFO if used together, but they shift every element, so they are the slow way to build a stack.
    • Forgetting self.. A bare data = [] in the constructor is a local variable that is gone when the constructor returns, and the other methods can't see it.
    • A shared list. Writing the list at class level, outside __init__, would give every stack the same list. Creating it in the constructor keeps each stack separate.
    • Printing instead of returning. pop, peek and size return their answers. The driver does the printing.

    Testing

    • Push 1 and 2, then call peek() twice and size(): the top is 2 both times and the size is 2.
    • Push 5 on one stack and leave another untouched: their sizes are 1 and 0.
    • Push 3, 1, 4 on top of a 5 and pop until size() reaches 0: the values come out as [4, 1, 3, 5], the reverse of the pushing order.
    • Call pop() on a new stack: IndexError.
    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free