Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
What is the first thing that comes to your mind when you hear the word stack?
You’re probably thinking of a stack of books, aren’t you? Well, the data structure stack is similar to a stack of books.
Like a pile of books, a data structure is used to store data in an organised manner to be accessed easily.
While picking up a book from a stack, is it possible to pull out a book from the middle without toppling the entire pile?
It isn’t. We have to go through all the books on top to get one from the middle. In other words, the last book added to the pile will be the first one picked up.
Similarly, a stack is a data structure that organises data such that the data last entered is accessed first. This is known as Last In First Out or LIFO.
Thus, to define it,
A stack is a Data Structure that works on the Last In First Out (LIFO) principle.
There are various functions associated with stacks. They are:
Function
Description
empty( )
It checks whether a stack is empty.
size( )
It returns the number of elements in the stack.
top( )
It returns the topmost element in the stack.
push(element)
It adds the value passed as a parameter to the stack.
pop( )
It deletes the topmost element in the stack.
The stack data structure and all the associated functions can be implemented in most programming languages, including the ones commonly used by us like C, C++, Java, and Python. In this article, we will learn about a stack in Python.
Lists are an essential feature in Python used to store data of different types together like an array. So, lists can store a block of data and can therefore be used as a stack.
To create a stack using a list, we will simply create a list as we usually do.
stack = [1, 2, 3, 4, 5]
You can also try this code with Online Python Compiler
This method is used to check if the stack is empty.
While creating a stack in Python with lists, we will use the bool( ) method, which takes a list as a parameter. This method returns a boolean value depending on whether the list is empty.
For example,
stack = [1,2,3,4,5]
print(bool(stack))
You can also try this code with Online Python Compiler
Here, len(stack) gives us the length of the stack, i.e., 5. So the element present in the index 5 - 1 = 4 in the list will be printed. That element is the last, as seen below.
push( )
To add an element to a stack in Python, we will have to add it to the end of our list. To do that, there is a predefined method in Python - append( ).
In Python, a pop( ) method takes an index as a parameter and removes the element in that index from the list.
In a stack in Python, we want to remove only the last element. So, to do that, we won’t give any parameter to the function, and the last element in the list will be popped as it happens in a stack.
Implementing a stack in Python with a list may seem easy, but it has a big disadvantage.
Like arrays, lists store the data in contiguous memory locations. So, if a lot of data is added to the stack, it may grow bigger than its memory block. Due to this reason, the working of the stack may slow down.
To overcome this problem, there is a faster alternative.
Python provides a container class used to store collections of data - the collection module. There is a deque class in the collection module that we can use to implement stacks in Python. The general syntax for that is:
from collections import deque
stack = deque( )
You can also try this code with Online Python Compiler
The rest of the standard methods in a stack using deque are the same as a list! Let’s see it for ourselves in the code below:
from collections import deque
stack = deque()
#pushing elements to stack
stack.append(1)
stack.append(2)
stack.append(3)
stack.append(4)
stack.append(5)
print("Stack:",list(stack))
#to check if stack is empty
print("Does stack have elements? T/F",bool(stack))
#to find the size of the stack
print("Size is",len(stack))
#to print the topmost element
print("Top is",stack[-1])
#to pop an element
print(stack[-1],"is popped")
stack.pop()
print("Stack:",list(stack))
You can also try this code with Online Python Compiler
Stack: [1, 2, 3, 4, 5]
Does stack have elements? T/F True
Size is 5
Top is 5
5 is popped
Stack: [1, 2, 3, 4]
With this, we finish learning how to use a list and the deque class as a stack in Python, but are these the only way?
Let us learn the next method then!
Stack in Python Using the Queue Module
There is another module available in Python called Queue. This can also be used to implement a stack in Python.
The queue model provides an additional feature of providing bounds to the stack.
We can specify the size by passing a parameter maxsize to the LifoQueue( ) method. maxsize is an integer that sets the upperbound limit on the number of items that can be placed in the queue. Insertion will block once this size has been reached, until queue items are consumed. If maxsize is less than or equal to zero, the queue size is infinite.
The general syntax to create a stack using the queue module is as follows:
from queue import LifoQueue
stack = LifoQueue(maxsize=0)
You can also try this code with Online Python Compiler
Let’s see how the standard methods in a stack are used here next. Must Read Python List Operations
Implementation of the Standard Stack Functions
empty( )
The empty( ) function can check if the stack is empty, as shown below. Unlike the bool( ) method we used previously, this method returns True if the stack is empty and False if it isn’t.
from queue import LifoQueue
stack = LifoQueue()
print(stack.empty())
You can also try this code with Online Python Compiler
Note: Here, the stack size is 0 even though we set the max size as 5 because there are no elements in the stack. Once we push elements to the stack, the qsize( ) method returns the number of elements present.
put( )
Here, the method to push elements to the stack is put( ). Here, if the stack has reached its maximum capacity, it will wait for space to push the element. It is used as shown below:
from queue import LifoQueue
stack = LifoQueue(maxsize=5)
stack.put(1)
stack.put(2)
stack.put(3)
stack.put(4)
stack.put(5)
#task_done shows a message after the operations on the stack are completed
stack.task_done
You can also try this code with Online Python Compiler
<bound method Queue.task_done of <queue.LifoQueue object at 0x7f9d3848ad50>>
Another method that can be used here is put_nowait( ). This method pushes an element into the stack if there is space, and if there isn’t space, it raises an error and terminates execution.
---------------------------------------------------------------------------
Full Traceback (most recent call last)
<ipython-input-34-0dad904af3c6> in <module>()
6 stack.put(4)
7 stack.put(5)
----> 8 stack.put_nowait(6)
get( )
The get( ) method pops and returns the topmost element in the stack. This method will also wait until an element is available if it is called when the stack is empty.
Note: Try using the put( ) and pop( ) methods after the size of the stack has exceeded, or the stack is empty, respectively.
full( )
An additional method exists for stacks in Python using the queue module - the full( ) function. This function checks whether the stack has reached its maximum capacity or, in other words, whether there is a maxsize number of elements in the stack.