Implement a Stack using a list

Implement a Stack using a list

A stack can be implemented using a simple list in python. My first attempt at creating a Stack in python looks like this:

# Implement a Stack using a list
class Stack():
    def __init__(self):
        self.items = list()

    def push(self, element):
        self.items.append(element)

    def pop(self):
        # check if stack is not empty
        if self.size() != 0:
            return self.items.pop()
        else:
            return None

    def size(self):
        return len(self.items)

    def top(self):
        if self.size() != 0:
            return self.items[-1]
        else:
            return None

    def __repr__(self):
        s = "---top---\n"
        s += " \n".join(str(i) for i in self.items[::-1])
        s += "\n---bottom---"

        return s

I would like you to note a few things here:

  • Check the pop() and top() logic that I wrote here. While this works, take a look at the one written below.
  • Secondly, I didn’t inherit from Object. Doing so has some benefits. Read it on realpython.
  • Thirdly, notice the use of __repr__. When someone calls this object, then they will see this string, instead of seeing a memory location. One thing to remember when using repr is that it should always return a string.

Better way to create a Stack

class Stack(object):
    def __init__(self):
        self.items = list()

    def push(self, item):
        self.items.append(item)

    def pop(self):
        if self.size() == 0:
            return None
        return self.items.pop()

    def top(self):
        if self.size() == 0:
            return None
        return self.items[-1]

    def size(self):
        return len(self.items)  

    def __repr__(self):
        s = "---top---\n"
        s += " \n".join(str(i) for i in self.items[::-1])
        s += "\n---bottom---"

        return s

Output

stack = Stack()
stack.push(19)
stack.push(199)
stack.push(1999)
print(stack)
---top---
1999
199
19
---bottom---
# get the top element
stack.top()
1999
stack
---top---
1999
199
19
---bottom---
# pop the elements
stack.pop()
1999
stack
---top---
199
19
---bottom---
print(stack.pop())
print(stack.pop())
print(stack.pop())
print(stack.size())
print(stack)
199
19
None
0
---top---

---bottom---