Stack Data Structure in Python

Want to excel in java coding? Practice with these Java Programs examples with output and write any kind of easy or difficult programs in the java language

Stacking objects means putting them on top of one another in the English language. This data structure allocates memory in the same manner.

Data structures are essential for organizing storage in computers so that humans can access and edit data efficiently. Stacks were among the first data structures to be defined in computer science. In layman’s terms, a stack is a linear accumulation of items. It is a collection of objects that provides fast last-in, first-out (LIFO) insertion and deletion semantics. It is a modern computer programming and CPU architecture array or list structure of function calls and parameters. Elements in a stack are added or withdrawn from the top of the stack in a “last in, first out” order, similar to a stack of dishes at a restaurant.

Unlike lists or arrays, the objects in the stack do not allow for random access.

Stack Data Structure in Python

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

1)What is the purpose of Stack and when do we use it?

Stacks are simple data structures which enable us to save and retrieve data successively.

In terms of performance, insert and remove operations should take O(1) time in a suitable stack implementation.

Consider a stack of books to grasp Stack at its most fundamental level. You place a book at the top of the stack, so the first one picked up is the last one added to the stack.

Stacks have many real-world applications; understanding them allows us to address numerous data storage challenges in a simple and effective manner.

Assume you’re a programmer working on a brand-new word processor. You must provide an undo functionality that allows users to reverse their activities all the way back to the start of the session. For this circumstance, a stack is an excellent choice. By pushing it to the stack, we can record every action taken by the user. When a user wants to undo an action, they can pop the appropriate item off the stack.

2)Ways to implement stack data structure in Python?

Python stacks can be implemented in Python by:

  • Using the List data structure that comes with the program. The List data structure in Python has methods for simulating both stack and queue operations.
  • Using the deque library, which combines the functions of a stack and a queue into a single object.
  • using  queue.LifoQueue Class.

As previously stated, we can use the “PUSH” operation to add items to a stack and the “POP” action to remove objects from a stack.

3)Basic methods of stack

The following methods are widely used with the stack in Python.

empty() :If the stack is empty, empty() returns true. It takes time complexity O(1).
size()   : is a function that returns the stack’s length. It takes time complexity O(1).
top() : This function returns the address of the stack’s last member. It takes time complexity O(1).).
push(r) : Pushes the element ‘r’ to the end of the stack – It takes time complexity O(1).
pop() : This procedure removes the stack’s topmost member. It takes time complexity O(1).

4)Working of Stack

The following is how the operations work:

  • The TOP pointer is used to maintain track of the stack’s top member.
  • We set the stack’s value to -1 when we first created it so that we can check if it’s empty by comparing          TOP == -1.
  • When we push an element, the value of TOP is increased, and the new element is placed at the position indicated to by TOP.
  • The element specified by TOP is returned and its value is reduced if an element is popped.
  • We check if the stack is already full before pushing.
  • We verify if the stack is already empty before popping it.

5)Implementation of stack

1)Implementation of integer stack

Below is the implementation:

# implementing stack data structure in Python


# Creating new empty stack
def createStack():
    Stack = []
    return Stack
# Checking if the given stack is empty or not


def isEmptyStack(Stack):
    return len(Stack) == 0


# appending elements to the stack that is pushing the given element to the stack
def pushStack(stack, ele):
    # appending the given element to the stack using append() function
    stack.append(ele)
    # printing the newly inserted/appended element
    print("New element added : ", ele)


# Removing element from the stack using pop() function
def popStack(stack):
  # checking if the stack is empty or not
    if (isEmptyStack(stack)):
        return ("The given stack is empty and we cannot delete the element from the stack")
    # if the stack is not empty then remove / pop() element from the stack
    return stack.pop()

# function which returns the top elememt in the stack


def topStack(stack):
  # returning the top element in the stack
    return stack[-1]


# creating a new stack and performing all operations on the stack
# creating new stack
st = createStack()
# adding some  random elements to the stack
pushStack(st, 5)
pushStack(st, 1)
pushStack(st, 9)
pushStack(st, 2)
pushStack(st, 17)
# removing element from stack
print(popStack(st), "is removed from stack")
# printing the stack after removing the element
print("Printing the stack after modification", st)
# printing the top element from the stack
print("The top element from the stack is ", topStack(st))

Output:

New element added :  5
New element added :  1
New element added :  9
New element added :  2
New element added :  17
17 is removed from stack
Printing the stack after modification [5, 1, 9, 2]
The top element from the stack is  2

2)Implementation of string stack

Below is the implementation of the above approach:

# implementing stack data structure in Python


# Creating new empty stack
def createStack():
    Stack = []
    return Stack
# Checking if the given stack is empty or not


def isEmptyStack(Stack):
    return len(Stack) == 0


# appending elements to the stack that is pushing the given element to the stack
def pushStack(stack, ele):
    # appending the given element to the stack using append() function
    stack.append(ele)
    # printing the newly inserted/appended element
    print("New element added : ", ele)


# Removing element from the stack using pop() function
def popStack(stack):
  # checking if the stack is empty or not
    if (isEmptyStack(stack)):
        return ("The given stack is empty and we cannot delete the element from the stack")
    # if the stack is not empty then remove / pop() element from the stack
    return stack.pop()

# function which returns the top elememt in the stack


def topStack(stack):
  # returning the top element in the stack
    return stack[-1]


# creating a new stack and performing all operations on the stack
# creating new stack
st = createStack()
# adding some  random elements to the stack
pushStack(st, "hello")
pushStack(st, "this")
pushStack(st, "is")
pushStack(st, "BTechGeeks")
pushStack(st, "python")
# removing element from stack
print(popStack(st), "is removed from stack")
# printing the stack after removing the element
print("Printing the stack after modification", st)
# printing the top element from the stack
print("The top element from the stack is ", topStack(st))

Output:

New element added :  hello
New element added :  this
New element added :  is
New element added :  BTechGeeks
New element added :  python
python is removed from stack
Printing the stack after modification ['hello', 'this', 'is', 'BTechGeeks']
The top element from the stack is  BTechGeeks

Related Programs: