Stack Implementation in Python

In this source code example, we will write a code to implement the Stack data structure in Python.

A stack is an ordered list in which insertion and deletion are done at one end, called a top. The last element inserted is the first one to be deleted. Hence, it is called the Last in First out (LIFO) or First in Last out (FILO) list.

Stack Implementation in Python

Main stack operations

Push Operation:
The process of putting a new data element onto the stack is known as a Push Operation.

Pop Operation:
Accessing the content while removing it from the stack, is known as a Pop Operation.

Other stack operations:

  • int peek(): Returns the top-most element of the stack
  • int size(): Returns the number of elements stored in the stack.
  • int isEmpty(): Indicates whether any elements are stored in the stack or not.
Here is the complete source code to implement the Stack data structure in Python:

class Stack(object):
    def __init__(self, limit = 10):
        self.stack = []
        self.limit = limit

    # for printing the stack contents
    def __str__(self):
        return ' '.join([str(i) for i in self.stack])

    # for pushing an element on to the stack
    def push(self, data):
        if len(self.stack) >= self.limit:
            print('Stack Overflow')
        else:
            self.stack.append(data)

    # for popping the uppermost element
    def pop(self):
        if len(self.stack) <= 0:
            return -1
        else:
            return self.stack.pop()

    # for peeking the top-most element of the stack
    def peek(self):
        if len(self.stack) <= 0:
            return -1
        else:
            return self.stack[len(self.stack) - 1]

    # to check if stack is empty
    def isEmpty(self):
        return self.stack == []

    # for checking the size of stack
    def size(self):
        return len(self.stack)

if __name__ == '__main__':
    myStack = Stack()
    for i in range(10):
        myStack.push(i)
    print(myStack)
    myStack.pop()           # popping the top element
    print(myStack)
    myStack.peek()          # printing the top element
    myStack.isEmpty()
    myStack.size()

Output:

0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8

Free Spring Boot Tutorial - 5 Hours Full Course


Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course