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
Stackdeclares one type parameter- Items come out last in, first out
peekdoes not remove, andlencountslenfollows pushes and pops, and a stack can be reused after emptying- An empty stack raises
IndexError - 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.