Stack Data Structure with Python
One of most used Data Structure in day to day life is Stack and Queue data structure. In this blog you will see Stack data structure.
So, let's try to simplify stack for you...
Let's understand stack with an example, Suppose you are in kitchen and you took a plate and kept it on kitchen now you took another plate and kept over first plate. You didn't stop here you kept 25 plates on that plate. If I say you to take out 14th plate so what will you do?
You start removing plates from upper side right so you remove one plate from top and then another and you do it until you wouldn't get 14th plate.
So, Stack is a user-defined data structure in which last element will come first while removing element and first element in last. This is also called as First In Last Out algorithm.
We can solve stack problems in 2 ways, first one is list method and second one is using collections.
Let's check this by one program of notebooks so you can better understand about list method:-
# Creating an empty stack
stack = []
# Inserting value inside the stack
stack.append("Notebook 1")
stack.append("Notebook 2")
stack.append("Notebook 3")
stack.append("Notebook 4")
stack.append("Notebook 5")
stack.append("Notebook 6")
# Print the stack
print(stack)
# Let's remove the values from stack
print("Removing: ",stack.pop())
print("Removing: ",stack.pop())
print("Removing: ",stack.pop())
print(stack)
Here you can understand every process as comment is inserted but let's see what is append and pop method?
In stack you will mostly work on push and pop methods, push method is use to insert value to the top and pop method is use to delete the value from the top.
here we are using list instead of arrays so list has it's own insertion method i.e. append, it insert values inside the list. and pop remove the element from the end side.
Output will be:
['Notebook 1', 'Notebook 2', 'Notebook 3', 'Notebook 4', 'Notebook 5',
'Notebook 6']
Removing: Notebook 6
Removing: Notebook 5
Removing: Notebook 4
['Notebook 1', 'Notebook 2', 'Notebook 3']
Hope it help you to understand stack Data Structure let's see a way more easy and lengthy example but for this example you have prior knowledge of Python's Functions..
stack = []
def push_element():
while True:
print("select the option to take
input:")
print("1.Int 2.Float 3.String
4.Bool 0.quit")
user_choice = int(input("Enter
choice to push the element: "))
if user_choice == 1:
int_element = int(input("Enter the
element: "))
stack.append(int_element)
print(stack)
elif user_choice == 2:
float_element = float(input("Enter
the element: "))
stack.append(float_element)
print(stack)
elif user_choice == 3:
string_element = input("Enter the
element: ")
stack.append(string_element)
print(stack)
elif user_choice == 4:
bool_element = int(input("Enter the
element: "))
if bool_element >= 1:
stack.append(True)
print(stack)
elif bool_element < 1:
stack.append(False)
print(stack)
elif user_choice == 0:
break
else:
print("Enter correct operations..")
def pop_element():
if not stack:
print("Stack is empty.")
else:
e = stack.pop()
print("Removed element:",e)
print(stack)
while True:
print("Select the operations: 1.push 2.pop 3.quit")
choice = int(input("Enter your
choice: "))
if choice == 1:
push_element()
elif choice == 2:
pop_element()
elif choice == 3:
break
else:
print("Please select the correct
operations.")
In this example you can see 2 functions are used, one for pushing value and another for deletion.
Here also you can see infinite while loop is running in which the conditions are generating and asking for the input, you can also end program by the quit buttons.
Output of the program is:
Select the operations: 1.push 2.pop 3.quit
Enter your choice: 1
select the option to take input:
1.Int 2.Float 3.String 4.Bool 0.quit
Enter choice to push the element: 1
Enter the element: 23
[23]
select the option to take input:
1.Int 2.Float 3.String 4.Bool 0.quit
Enter choice to push the element: 2
Enter the element: 23.4
[23, 23.4]
select the option to take input:
1.Int 2.Float 3.String 4.Bool 0.quit
Enter choice to push the element: 3
Enter the element: "CodeWithDevops"
[23, 23.4, '"CodeWithDevops"']
select the option to take input:
1.Int 2.Float 3.String 4.Bool 0.quit
Enter choice to push the element: 4
Enter the element: 1
[23, 23.4, '"CodeWithDevops"', True]
select the option to take input:
1.Int 2.Float 3.String 4.Bool 0.quit
Enter choice to push the element: 0
Select the operations: 1.push 2.pop 3.quit
Enter your choice: 2
Removed element: True
[23, 23.4, '"CodeWithDevops"']
Select the operations: 1.push 2.pop 3.quit
Enter your choice: 3
Now let's see collections, collections are in built library in Python, it contains queue and their methods to solve these kind of problems.
To use collections you have to import this module inside your program. If you are familiar with Java then you know importing libraries, basically import is a keyword that helps our program to use Python pre-defined libraries and modules.
First import collections and from this collection use deque method to solve stack problems.
Let's see an example to understand:-
import collections
stack = collections.deque()
print(stack)
stack.append(10)
stack.append(20)
stack.append(30)
stack.append(40)
stack.append(50)
print(stack)
print("Removing ",stack.pop())
print("Removing ",stack.pop())
print("Removing ",stack.pop())
print(stack)
As you can see above example in first line collections module is imported, then a empty list is created by a method of collections called deque().
as you know that to append values inside list you have to use append method, o use it and insert values inside stack list.
To remove the value same as above you seen use pop method.
Output of this program will be:-
deque([])
deque([10, 20, 30, 40, 50])
Removing 50
Removing 40
Removing 30
deque([10, 20])
Next thing is queue module this is also used to solve stack problem, import queue module, from the module you have to use LifoQueue method to solve the stack problem. Let's understand this problem with an example:-
import queue
stack = queue.LifoQueue()
stack.put(10)
stack.put(20)
stack.put(30)
stack.put(40)
stack.put(50)
print(stack)
stack.get()
stack.get()
stack.get()
print(stack)
As you can see this problem first queue is imported then LifoQueue is used from queue module(you can also give some value inside LifoQueue's braces as limit of the stack) then LifoQueue provides put() and get() methods instead of append and pop methods put method append the value and get method removes the value.
Output will be:-
<queue.LifoQueue object at 0x000001BE5FEDAFA0
50
40
30
<queue.LifoQueue object at 0x000001BE5FEDAFA0>
As you can see queue is an object so you cannot print it, that's why is showing the memory location instead of list.
That's it for this blog we will continue with Queue data structure in next blog.