Editor

A Stack Class

#236 · Classes · Beginner · 35 XP · about 8 min

A stack is a pile where the last thing you put on is the first thing you take off, like a pile of plates. Build a Stack class with these methods:

  • Stack() makes an empty stack.
  • push(item) puts item on top.
  • pop() removes the top item and returns it.
  • peek() returns the top item without removing it.
  • is_empty() returns True when the stack holds nothing, and False otherwise.
  • size() returns how many items the stack holds.

Calling pop() or peek() on an empty stack raises an IndexError.

Examples

s = Stack()
s.push('a')
s.push('b')
s.peek()       # returns 'b'
s.pop()        # returns 'b'
s.size()       # returns 1
s.is_empty()   # returns False
s.pop()        # returns 'a'
s.pop()        # raises IndexError

Note

Every stack keeps its own items: pushing onto one stack never changes another one.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.