Python Examples

Stack in Python



A stack is a linear dynamic data structure that follows Last-In/First-Out (LIFO) principle. In a stack, addition of a new element and deletion of an element occurs at the same end which implies that the element which is added last in the stack will be the first to be removed from the stack.

Features of stack

  • It is a dynamic data structure.
  • It has dynamic size.
  • It uses dynamic memory allocation.

Operations of a stack

  • isEmpty(): Checks whether the stack is empty or not.
  • size(): Returns the size of the stack.
  • topElement(): Returns the top element of the stack.
  • push(x): Adds a new element ‘x’ at the top of the stack. Consequently, size of the stack increases by 1.
    Stack Push
  • pop(): Deletes the top element of the stack. Consequently, size of the stack decreases by 1.
    Stack Pop

Implementation of Stack

# function to create stack
def CreateStack():
  stack = []
  return stack

# create function to check whether 
# the stack is empty or not
def isEmpty(stack):
  if(len(stack) == 0):
    print("Stack is empty.")
  else:
    print("Stack is not empty.") 
    
#create function to return size of the stack       
def size(stack):
  return len(stack)

#create function to add new element       
def push(stack, newElement):
  stack.append(newElement)
  print(newElement, "is added into the stack.")

#create function to delete top element       
def pop(stack):
  print(stack.pop(), "is deleted from the stack.")

#create function to get top element       
def topElement(stack):
  return stack[len(stack) - 1]


# test the code                 
MyStack = CreateStack()

push(MyStack, 10)
push(MyStack, 20)
push(MyStack, 30)
push(MyStack, 40)

pop(MyStack)
isEmpty(MyStack)

The above code will give the following output:

10 is added into the stack.
20 is added into the stack.
30 is added into the stack.
40 is added into the stack.
40 is deleted from the stack.
Stack is not empty.