Python | Using List as Stack: Here, we will figure out how to utilize Lists as Stacks in Python? Here, we are executing stack program by utilizing list.
As a matter of first importance, we should mindful with the Stack – the stack is a straight information structure that takes a shot at LIFO system for example Toward the end In First Out (that implies Last embedded thing will be evacuated (popped) first).
In this way, to execute a stack, essentially we need to complete two things:
- Inserting (PUSH) components toward the finish of the list
- Removing (POP) components from the finish of the list
, for example, the two activities ought to be done from one end.
In Python, we can execute a stack by utilizing list strategies as they have the capacity to embed or evacuate/pop components from the finish of the list.
A strategy that will be utilized:
- append(x): Appends x toward the finish of the list
- pop(): Removes last components of the list
Program to utilize 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]