Implement stack using list in Python
In this tutorial, we shall implement a stack using list in Python. A stack is a Linear Data Structure that uses a LIFO (Last In First Out) methodology. Unlike other programming languages, Python does not have a specified stack data structure but the lists in Python pretty much work like stacks. Python’s built-in lists support push and pop operations of the stack. Stack’s insert operation is called push and delete operation is called pop.
Stack Operations:
- push(a): pushes an element ‘a’ at the top of the stack.
- pop(): removes the recently added (topmost) element in the stack.
- empty(): returns boolean value whether the stack is empty or not.
- top(): prints the recently added (topmost) element of the stack.
- size(): prints the size of the stack, zero if empty.
>>>s = [1,2,3] >>>s.push(4) >>>s [1,2,3,4] >>>s.pop() 4 >>>s.top() 3 >>>s [1,2,3] >>>s.size() 3 >>>s.empty() False
Python built-in list operation append() and pop() used to push and pop elements in the stack respectively. For remaining operations like empty, top, size, we define functions to implement them. All the operations can be implemented in O(1) complexity each.
Implement stack using list in Python
#Stack using list stack = [] #Function to print top element of stack def top(stack): if stack != []: print(stack[-1] + " is top element") else: print("Stack Empty!!!") #Function to print size of stack def size(stack): print("Size of stack is " + str(len(stack))) #Function to check if a stack is empty def empty(stack): if stack == []: print("True") else: print("False") # append() function is used to push element in the stack stack.append('a') stack.append('b') stack.append('c') size(stack) print(stack) top(stack) # pop() function to pop element from stack in LIFO order print(stack.pop() + " is popped") print(stack) empty(stack) print(stack.pop() + " is popped") print(stack.pop() + " is popped") print(stack) empty(stack)
Output: Size of stack is 3 ['a', 'b', 'c'] c is top element c is popped ['a', 'b'] False b is popped a is popped [] True
I am Vamsi Krishna and you can find my other posts here:
Find bitonic point in given bitonic sequence in Python
Get all possible sublists of a list in Python
Also Read: numpy.stack() in Python with example.
Thank You for reading and Keep Learning 🙂
Leave a Reply