Just Tech Me At
March 26, 2023
A stack is a data structure that stores items adhering to a Last-In First-Out (LIFO) rule. With a stack, elements are inserted in sequence. Additionally, items are removed in a manner that complies with this sequential structure. That is, elements can only be added to the end (top) of the structure and removed from that end (top)of the structure. The insert and delete operations are accomplished using the append() and pop().
The append and pop methods are used to enforce LIFO behavior of stacks.
To add an element to the end of the stack, use the following syntax:
stack.append(x) #Add an item to the end of the stack.
To remove an element from the end of the stack, use the following syntax:
stack.pop() #removes and returns the last item in the stack.
Note that LifoQueue uses put() and get() in place of append() and pop() to add and remove data from the stack. With LifoQueue, to remove an element from the end of the stack, use the following syntax:
stack.put() #Add an item to the end of the stack
stack.get() #removes and returns the last item in the stack.
There are a number of ways to implement a Python stack. Below are three (3) common ways to implement a stack in Python.
When reviewing the three common ways to implement a stack, the last two options may seem a bit strange as there is also a data structure called queue. The thing to remember is that stacks and queues are all about "behavior." That is why the term "implementation" keeps popping up. The structures themselves can be created in many ways but it is how the structure behaves that determine whether it is a stack or queue or an average list.
stack = [] # create an empty stack
stack.append(1) # push 1 onto the stack
stack.append(2) # push 2 onto the stack
stack.pop() # remove and return 2 from the stack
from collections import deque
stack = deque() # create an empty stack
stack.append(1) # push 1 onto the stack
stack.append(2) # push 2 onto the stack
stack.pop() # remove and return 2 from the stack
from queue import LifoQueue
stack = LifoQueue() # create an empty stack
stack.put(1) # push 1 onto the stack
stack.put(2) # push 2 onto the stack
stack.get() # remove and return 2 from the stack
Stacks are a valuable data structure. They can improve the efficiency of your program. The operations for adding and removing elements have a time complexity of O(1). Stacks can be a perfect fit for rollback operations of applications. The downside to stacks is that you must traverse through the stack sequentially to access elements not located at the top or back of the structure. Nevertheless, understanding stack creation and how stacks behave are a vital skill for a Python developer to possess.
For more articles on Python data structures, see the following:
Visit Educative.io
Polish Your Python Skills. Visit Tutorials Point!
Visit DataCamp Today!