Stacks In Python 3

Implementation of Stacks

Implementation of stack using List

The implementation of stacks using list in python is the easiest of all programming languages. It offers a convenient set of methods to operate list as stack. The basic operations performed on the stacks are:

* Push operation / adding an element in the stack
* Pop operation / deleting an element from a stack
* Displaying all elements / traversal of elements

Creating a stack

The list methods available in python make it flexible and easy to implement stacks using lists. In python when we declare a list, it creates an address in the memory to hold any number of heterogeneous elements. Thus in order to create an empty stack , we need to use inbuilt function list() as given below.

Syntax:
Method:1
To create an empty stack/list
stack=list()

Method:2
To create an empty stack/list
stack=[]

Adding an element into a stack

Adding an element into stack is called PUSH operation. In Python , the list function append() is used to add an element into the stack.

Syntax:
list.append(n)
Where,
n : values to add in the list

Algorithm for PUSH Operation

1. start
2. take input for element to push(add) say n
n=input(“Enter element to push “)
3. stack.append(n)
4. end

Deletion of an element from a stack

Note: Before deleting an element it is important to check for an empty stack.

Before we delete/pop an element from stack or display/traverse elements of the stack it is important to check whether stack in empty or not. if the stack is not empty then only pop and traversal operations can be performed otherwise not.

In python, the list function pop() is used to pop/remove/delete elements from a stack.

Syntax:
stack.pop()
or
stack.pop(i)

Where
i: position

Note: if no index is mentioned by default topmost element is deleted.

Algorithm to check empty stack and perform pop operation

Method:1

1. start
2. n=len(stack)
we will find the length/number of elements in the stack
3. if(n==0):
print(“stack is empty”)
goto step 5
4. n1=stack.pop()
pop element top element and store it in n1
5. end

Method:2

1. start
2. n=len(stack)
we will find the length/number of elements in the stack
3. if not len(stack):
print(“stack is empty”)
goto step 5
4. n1=stack.pop()
pop element top element and store it in n1
5. end

Method:3

1. start
2. n=len(stack)
we will find the length/number of elements in the stack
3. if not stack:
print(“stack is empty”)
goto step 5
4. n1=stack.pop()
pop element top element and store it in n1
5. end

Traversing Stack Elements

Traversal is the operation of displaying all the elements of the stack. In traversal process elements from the top position get displayed first and then processed in reverse order.

Visitor Counter

0142290