Understanding Stacks in Python for Beginners

Carla Pico
Strategio
Published in
2 min readFeb 6, 2023

Python has built-in data structures and user-defined data structures it utilizes to organize data. In this article, we will be learning about a user-defined data structure and the breakdown of an example so we can further understand how stacks are used in Python.

LIFO(Last in First Out) AND FILO(First in Last Out).

What is a Stack

A stack is a linear data structure that observes the rules of LIFO (Last In First Out) and FILO (First in Last Out). Stacks are part of the user-defined data structures in Python as they allow users to “have full control over their functionality.” Stacks are built using arrays and add and delete methods using the operations push and pop respectively.

Stack Operations

Two of the most common operations we use in a Stack are:

  • Push is used to add data to the top of a stack. Time Complexity: O(1)
  • Pop is used to remove data from the top of a stack. Time Complexity: O(1)
# Function to create an empty stack.

# It initializes size of stack as 0

def createNewStack():
stack = []
return stack

# Function to determine the size of the stack


def lengthOfStack(stack):
return len(stack)

# Stack is empty if the length of the stack is 0


def stackIsEmpty(stack):
if lengthOfStack(stack) == 0:
return true

# Function to add an item to stack .
# It increases size by 1

def push(stack, item):
stack.append(item)


# Function to remove an item from stack.
# It decreases size by 1

def pop(stack):
if isEmpty(stack):
return
return stack.pop()

Python Challenge: Reverse A String

  • Create an empty stack.
  • One by one push all characters of a string to stack.
  • One by one pop all characters from the stack and put them back into the string.

# Python challenge to reverse a string using stack

# A stack based function to reverse a string

def reverseString(string):
n = len(string)

# Create a empty stack
stack = createStack()

# Push all characters of string to stack
for i in range(0, n, 1):
push(stack, string[i])

# Making the string empty since all characters are saved in stack
string = ""

# Pop all characters of string and put them back to string
for i in range(0, n, 1):
string += pop(stack)

return string

Feel free to leave below any comments or questions you may have regarding Stacks in Python and thank you for reading this article!

--

--