← Back to Python List

Question 1: Stack from List

Create a list of 10 integers. Write a program with separate user-defined functions to perform the following operations:

Solution

[Run Online]

# Q1. Write a program to accept a list of 10 integers and implement the following:
#     i)   PUSH_Div5(L, STACK) - Push elements divisible by 5 from list L into STACK
#     ii)  DISPLAY(STACK) - Display the current content of the stack
#     iii) POP(STACK) - Pop elements from the stack

# i) Push-item: Function to PUSH elements divisible by 5 into Stack
def PUSH_Div5(L, STACK):
    for num in L:
        if num % 5 == 0:
            STACK.append(num)

    if len(STACK) == 0:
        print("No element divisible by 5 found in the list")


# ii) Display: Function to show the current content of the stack
def DISPLAY(STACK):
    if len(STACK) == 0:
        print("Stack is empty")
    else:
        print(STACK)


# iii) Pop: Function to POP elements from the stack
def POP(STACK):
    if len(STACK) == 0:
        print("Stack Underflow / No element to pop")
    else:
        print("Popping element:", STACK.pop())


# ---------- Main Program ----------

# Creating a list of 10 elements
L = []
print("Enter 10 integers:")
for i in range(10):
    n = int(input("Enter a number: "))
    L.append(n)

print("Original List:", L)

# Creating empty stack
STACK = []

# Calling functions
PUSH_Div5(L, STACK)
DISPLAY(STACK)  # Showing the stack after pushing
POP(STACK)  # Popping one element
DISPLAY(STACK)  # Showing stack after one pop