DEV Community

Cover image for Stack in python
Dana
Dana

Posted on

Stack in python

A stack is a linear data structure that follows the principle of Last In First Out (LIFO) This means the last element inserted inside the stack is removed first.

LIFO Principle of Stack:

  • putting an item on top of the stack is called push.
  • removing an item is called pop.

Stack Push and Pop Operations

Basic Operations of Stack:

  • Push: Add an element to the top of a stack.
  • Pop: Remove an element from the top of a stack.
  • IsEmpty: Check if the stack is empty.
  • IsFull: Check if the stack is full.
  • Peek: Get the value of the top element without removing it.

Working of Stack Data Structure:

  • A pointer called TOP is used to keep track of the top element in the stack.
  • When initializing the stack, we set its value to -1 so that we can check if the stack is empty by comparing TOP == -1.
  • On pushing an element, we increase the value of TOP and place the new element in the position pointed to by TOP.
  • On popping an element, we return the element pointed to by TOP and reduce its value.
  • Before pushing, we check if the stack is already full.
  • Before popping, we check if the stack is already empty.

So,

  • empyty stack => (empty bottle) => top = -1
  • stack[1] => (push = 1) => top = 0
  • stack[2] => (push = 2) => top = 1
  • stack[3] => (push = 3) => top = 2
  • return stack[2] => (pop = 3) => top = 1

Working of Stack Data Structure

Stack Implementations in Python

"""Stack code."""


def create_stack():
    """Creating a stack."""
    stack = []
    return stack


def check_empty(stack):
    """Creating an empty stack."""
    return len(stack) == 0


def push(stack, item):
    """Adding items into the stack."""
    stack.append(item)
    print("Pushing item " + item)


def pop(stack):
    """Removing an element from the stack."""
    if check_empty(stack):
        """Check for empty stack."""
        return "stack is empty"

    return stack.pop()


stack = create_stack()
push(stack, str(1))
push(stack, str(2))
push(stack, str(3))
push(stack, str(4))
push(stack, str(5))

print("popped item: " + pop(stack))
print("stack after popping an elements " + str(stack))


Enter fullscreen mode Exit fullscreen mode

the output

Pushing item 1
Pushing item 2
Pushing item 3
Pushing item 4
Pushing item 5
popped item: 5
stack after popping an elements ['1', '2', '3', '4']
Enter fullscreen mode Exit fullscreen mode

Top comments (0)