Command Palette

Search for a command to run...

Hectal
Phase 10: Type Hints and Modern Python
Python · Exercise 2 of 5 PreviousNext
Intermediate

A generic Stack

A stack is a pile where the last item you put on is the first you take off. Write a generic class Stack[T] using the Python 3.12 syntax (Topic 10.4). It needs four methods: push(item) adds an item, pop() removes and returns the last item pushed, peek() returns the last item without removing it, and __len__ returns how many items are inside.

Popping or peeking an empty stack should raise IndexError. The lines at the bottom of the starter push 1, 2, 3 and print the popped item; they should print 3.

What Check tests

  1. Stack declares one type parameter
  2. Items come out last in, first out
  3. peek does not remove, and len counts
  4. len follows pushes and pops, and a stack can be reused after emptying
  5. An empty stack raises IndexError
  6. The program prints 3

Stuck? One hint at a time

The solution unlocks after your first Check. Try first: that is where the learning happens.

main.py
Sign in to run your code.

Output

Press Run to see what your program prints.