Skip to content


Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Cannot retrieve contributors at this time

64 lines (46 sloc) 2.075 kb

A real stack collection for Python. Sometimes you don't want something that walks like a duck, that swims like a duck and that quacks like a duck. Sometimes you just want a duck!

There are unit tests available in There is one example of using the stack to implement a basic reverse polish notation calculator in the examples folder.


Some algorithms are best implemented using a stack and while it is possible to use a built-in list() like a stack, I find the semantics of peek, my_list[-1], to be detracting from an algorithm's implementation. This Stack implementation provides the basic stack operations you learned in CS101:

  • .push()
  • .peek()
  • .pop()
  • .is_empty()

It also provides some conveniences:

  • .push(*objs) <-- push splat, multiple objects in one push
  • .reverse() <-- reverse the order of the stack. It is surprising how often you need to do this
  • .iter_pop() <-- returns a generator that pops the whole stack one item at a time

I don't recommend using this Stack implementation when your stack usage only loosely resembles a traditional stack though. For instance, when you are inserting into the middle of the list, popping the end of it and then slicing it out to chunks, etc... in those cases just tough it out with a regular list object as I think it will be faster for other Pythonistas to read your code.


from stack import Stack, EmptyStackException

stack = Stack()

# push one item

# push many items
stack.push("b", "c")

# peek the top item

# check the length

# reverse the stack in place

# pop an item

# pop all of the items
items = [i for i in stack.iter_pop()]

# catch those exceptions, your algorithm should not try to do this!
empty_stack = Stack()
except EmptyStackException as ese:
  print("Why'd ya do it man?")
Jump to Line
Something went wrong with that request. Please try again.