How to implement stack in Python 2023

Stack implementation in Python  (Push(),Pop() and Peek())

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. It has three primitive operations:

  1. Push: Add an element to the stack
  2. Pop: Remove an element from the stack
  3. Peek: Get the topmost element of the stack

Python, a stack is implemented using a list object.

  1. To push an item in the stack, use the list function append list.append(item)
  2. To pop an item in the stack, use the list function pop list.pop()
  3. To get the top most item in the stack, write list[-1]

Stack implementation in python- Latest Tech Updates

The following illustration explains the concept:

list=[]

list.append(1) # append 1

print("push:",list)

list.append(2) # append 2

print("push:",list)

list.append(3) # append 3

print("push:",list)

list.pop() # pop 3

print("pop:",list)

print("peek:",list[-1]) # get top most element

list.pop() # pop 2

print("pop:",list)

print("peek:",list[-1]) # get top most element

Also Check seek() and tell() in python class 12 

Stack Implementation using Python

We Will try to implement this data structure in the Python programming language. There are various ways to implement the stack data structure in Python. We will do it in the easiest way, which is by using a list.

The list is an in-built data structure in Python, and it can be used as a stack. We can use the append() method to push elements to the top of the stack. We also have the pop() method which removes the items in LIFO order. 

Applications of Stack Data Structure

Stack is a simple data structure to implement, it is very powerful. The most common uses of a stack are:

  1. To reverse a word - Put all the letters in a stack and pop them out. Because of the LIFO order of stack, you will get the letters in reverse order.
  2. In compilers - Compilers use the stack to calculate the value of expressions like 2 + 4 / 5 * (7 - 9) by converting the expression to prefix or postfix form.
  3. In browsers - The back button in a browser saves all the URLs you have visited previously in a stack. Each time you visit a new page, it is added on top of the stack. When you press the back button, the current URL is removed from the stack, and the previous URL is accessed.

Example Program-1

Given below is the Python code that implements the stack data structure.

stack = []

max_size = int(input("Enter the max limit of the stack: "))

while True:

    print("What do you want to do? ")

    print("1. Push")

    print("2. Pop")

    print("3. Exit")

    choice = int(input("Enter your choice: "))

    if choice == 1:

        if(len(stack) == max_size):

            print("Stack is full.")

        else:

            value = input("Enter the value: ")

            stack.append(value)

        print('Stack after elements are pushed:', stack)

    elif choice == 2:

        if(len(stack) == 0):

            print("Stack is empty.")

        else:

            stack.pop()

        print('Stack after elements are popped:', stack)

        elif choice == 3:

        break

    else:

        print("Invalid choice.")

    print()


Output:

Enter the max limit of the stack: 2

What do you want to do? 

1. Push

2. Pop

3. Exit

Enter your choice: 1

Enter the value: Red

Stack after elements are pushed: ['Red']

What do you want to do? 

1. Push

2. Pop

3. Exit

Enter your choice: 1

Enter the value: Blue

Stack after elements are pushed: ['Red', 'Blue']

What do you want to do? 

1. Push

2. Pop

3. Exit

Enter your choice: 1

Stack is full.

Stack after elements are pushed: ['Red', 'Blue']

What do you want to do? 

1. Push

2. Pop

3. Exit

Enter your choice: 2

Stack after elements are popped: ['Red']

What do you want to do? 

1. Push

2. Pop

3. Exit

Enter your choice: 2

Stack after elements are popped: []

What do you want to do? 

1. Push

2. Pop

3. Exit

Enter your choice: 2

Stack is empty.

Stack after elements are popped: []

What do you want to do? 

1. Push

2. Pop

3. Exit

Enter your choice: 3


Example Program -2

 Stack implementation in python

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

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

# Adding elements into the stack
def push(stack, item):
    stack.append(item)
    print("pushed item: " + item)
# Removing an element from the stack
def pop(stack):
    if (check_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))
print("popped item: " + pop(stack))
print("stack after popping an element: " + str(stack))

Search Related Tags 

  • push and pop operation in stack in data structure
  • write a python program to implement push and pop operation using list
  • queue in python
  • stack in python
  • stack program in python
  • stack in python w3schools
  • stack in python pdf
  • write a python program to implement stack using list class 12
  • stack operations in python
  • stack implementation using list in python
  • peek in stack python
  • queue in python
  • stack top in python
  • stack program in python class 12 pdf
  • check if stack is empty python
  • stack implementation using list in python
  • stack in python pdf
  • write a python program to implement push and pop operation using list
  • stack in python w3schools
  • stack operations in python
  • stack in python using function
  • queue in python
  • stack top in python

If you any doubts, Please let me know

Previous Post Next Post

Contact Form