Home »
Python »
Python programs
Using List as Stack in Python
Python | Using List as Stack: Here, we are going to learn how to use Lists as Stacks in Python? Here, we are implementing stack program by using list.
Submitted by IncludeHelp, on September 22, 2018
First of all, we must aware with the Stack - the stack is a linear data structure that works on LIFO mechanism i.e. Last In First Out (that means Last inserted item will be removed (popped) first).
Thus, to implement a stack, basically we have to do two things:
- Inserting (PUSH) elements at the end of the list
- Removing (POP) elements from the end of the list
i.e. both operations should be done from one end.
In Python, we can implement a stack by using list methods as they have the capability to insert or remove/pop elements from the end of the list.
Method that will be used:
- append(x) : Appends x at the end of the list
- pop() : Removes last elements of the list
Program to use list stack
# Python Example: use list as stack
# Declare a list named as "stack"
stack = [10, 20, 30]
print ("stack elements: ");
print (stack)
# push operation
stack.append(40)
stack.append(50)
print ("Stack elements after push opration...");
print (stack)
# push operation
print (stack.pop (), " is removed/popped...")
print (stack.pop (), " is removed/popped...")
print (stack.pop (), " is removed/popped...")
print ("Stack elements after pop operation...");
print (stack)
Output
stack elements:
[10, 20, 30]
Stack elements after push opration...
[10, 20, 30, 40, 50]
50 is removed/popped...
40 is removed/popped...
30 is removed/popped...
Stack elements after pop operation...
[10, 20]
TOP Interview Coding Problems/Challenges