Write a python program to implement a stack using list

Write a python program to implement a stack using list

Here, we are going to write a python program to implement a stack using list.Before implementing stack using list,first we will see what is stack. A stack is a data structure that stores items in an Last-In/First-Out manner. This is frequently referred to as LIFO. There are many ways to implement stack in python. I will tell you some of them. We can implement stack using linear list or queue or dequeue. There are two inbuilt function to add and remove data element from stack .

Pop : we can use pop() inbuilt function to remove element from stack in LIFO order.

Push : We can use push () inbuilt function to add element into stack. We can use append function to add element at the top of the stack. Here we are using append () function to insert new element to the top of the stack.

Python program to implement a stack using list

# Python program to
# demonstrate stack implementation
# using list

mystack = []

# append() function to push
# element in the stack
mystack.append('p')
mystack.append('y')
mystack.append('t')
mystack.append('h')
mystack.append('o')
mystack.append('n')

print('After inserting element into stack :')
print(mystack)

# pop() function to pop
# element from stack in
# LIFO order
print('\nElements popped from stack:')
print(mystack.pop())
print(mystack.pop())
print(mystack.pop())
print(mystack.pop())
print(mystack.pop())
print(mystack.pop())

print('\nStack after elements are popped:')
print(mystack)

# uncommenting print(stack.pop())
# will cause an IndexError
# as the stack is now empty


Output

After inserting element into stack :
['p', 'y', 't', 'h', 'o', 'n']

Elements popped from stack:
n
o
h
t
y
p

Stack after elements are popped:
[]
<