Stack data structure in python

I won't talk about the list structure as that's already been covered in this question. Instead I'll mention my preferred method for dealing with stacks:

I always use the Queue module. It supports FIFO and LIFO data structures and is thread safe.

See the docs for more info. It doesn't implement a isEmpty() function, it instead raises a Full or Empty exception if a push or pop can't be done.


No need to jump through these loops, See 5.1.1 Using Lists as Stacks

If you insist on having methods isEmpty() and push() you can do:

class stack(list):
    def push(self, item):
        self.append(item)
    def isEmpty(self):
        return not self

Stack follows LIFO mechanism.You can create a list and do a normal append() to append the element to list and do pop() to retrieve the element out of the list which you just inserted.


You are right to use composition instead of inheritance, because inheritance brings methods in that you don't want to expose.

class Stack:
  def __init__(self):
    self.__storage = []

  def isEmpty(self):
    return len(self.__storage) == 0

  def push(self,p):
    self.__storage.append(p)

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

This way your interface works pretty much like list (same behavior on pop for example), except that you've locked it to ensure nobody messes with the internals.

Tags:

Python