Stack as LIFO use case.
In computer science and programming a stack is an abstract linear data type that serves as a collection of elements that follows the principle of Last In First Out (LIFO).
Two main operations can be done with stacks:
- Push, which adds an element to the collection.
- Pop, which removes the most recently added element that was not yet removed.
Python Knowledge Base: Make coding great again.
- Updated:
2024-12-01 by Andrey BRATUS, Senior Data Analyst.
Stack Data Structure Python code:
Stack Data Structure Python code otput:
It is possible to represent stack data structure as the pile of plates, one on the top of another. You can put a new plate on top (push) or remove the top plate (pop). To reach the plate at the bottom you must first remove all the plates on top. The code below is the simple stack implementation using lists, it can be done using arrays also.
# Create a stack
def create_stack():
stack = []
return stack
# Empty stack
def check_empty(stack):
return len(stack) == 0
# Push element
def push(stack, item):
stack.append(item)
print("pushed: " + item)
# Pop element
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))
push(stack, str(5))
push(stack, str(6))
print("popped: " + pop(stack))
print("popped: " + pop(stack))
print("stack now: " + str(stack))
OUT:
pushed: 1
pushed: 2
pushed: 3
pushed: 4
pushed: 5
pushed: 6
popped: 6
popped: 5
stack now: ['1', '2', '3', '4']