Stack in Python
A stack is a linear dynamic data structure that follows Last-In/First-Out (LIFO) principle. In a stack, addition of a new element and deletion of an element occurs at the same end which implies that the element which is added last in the stack will be the first to be removed from the stack.
Features of stack
- It is a dynamic data structure.
- It has dynamic size.
- It uses dynamic memory allocation.
Operations of a stack
- isEmpty(): Checks whether the stack is empty or not.
- size(): Returns the size of the stack.
- topElement(): Returns the top element of the stack.
- push(x): Adds a new element ‘x’ at the top of the stack. Consequently, size of the stack increases by 1.
- pop(): Deletes the top element of the stack. Consequently, size of the stack decreases by 1.
Implementation of Stack
# function to create stack def CreateStack(): stack = [] return stack # create function to check whether # the stack is empty or not def isEmpty(stack): if(len(stack) == 0): print("Stack is empty.") else: print("Stack is not empty.") #create function to return size of the stack def size(stack): return len(stack) #create function to add new element def push(stack, newElement): stack.append(newElement) print(newElement, "is added into the stack.") #create function to delete top element def pop(stack): print(stack.pop(), "is deleted from the stack.") #create function to get top element def topElement(stack): return stack[len(stack) - 1] # test the code MyStack = CreateStack() push(MyStack, 10) push(MyStack, 20) push(MyStack, 30) push(MyStack, 40) pop(MyStack) isEmpty(MyStack)
The above code will give the following output:
10 is added into the stack. 20 is added into the stack. 30 is added into the stack. 40 is added into the stack. 40 is deleted from the stack. Stack is not empty.
Recommended Pages
- Python Program - To Check Prime Number
- Python Program - Bubble Sort
- Python Program - Selection Sort
- Python Program - Maximum Subarray Sum
- Python Program - Reverse digits of a given Integer
- Python - Swap two numbers
- Python Program - Fibonacci Sequence
- Python Program - Insertion Sort
- Python Program - Find Factorial of a Number
- Python Program - Find HCF of Two Numbers
- Python Program - To Check Whether a Number is Palindrome or Not
- Python Program - To Check Whether a String is Palindrome or Not
- Python Program - Heap Sort
- Python Program - Quick Sort
- Python - Swap Two Numbers without using Temporary Variable
- Python Program - To Check Armstrong Number
- Python Program - Counting Sort
- Python Program - Radix Sort
- Python Program - Find Largest Number among Three Numbers
- Python Program - Print Floyd's Triangle