How to implement stack in Python?

Implementing a Stack in Python: A Comprehensive Guide

Introduction

A stack is a fundamental data structure in computer science that follows the Last-In-First-Out (LIFO) principle. It is a linear data structure that stores elements in a specific order, where the last element added to the stack is the first one to be removed. In this article, we will explore how to implement a stack in Python, including the basic concepts, data structures, and methods used to create a stack.

What is a Stack?

A stack is a data structure that follows the LIFO principle, meaning that the last element added to the stack is the first one to be removed. This is in contrast to a queue, which follows the FIFO (First-In-First-Out) principle, where the first element added to the queue is the first one to be removed.

Basic Concepts

Before we dive into implementing a stack in Python, let’s cover some basic concepts:

  • Elements: In a stack, elements are the data that are stored. These elements can be of any data type, including strings, integers, floats, and more.
  • Operations: A stack supports basic operations such as push (adding an element to the top of the stack), pop (removing an element from the top of the stack), and peek (retrieving the top element without removing it).
  • Stack Size: The maximum number of elements that can be stored in a stack is limited by the stack size. If the stack size is exceeded, the last element added to the stack is discarded.

Implementing a Stack in Python

Here’s a step-by-step guide to implementing a stack in Python:

Step 1: Define the Stack Class

class Stack:
def __init__(self, max_size):
self.max_size = max_size
self.stack = []

def is_full(self):
return len(self.stack) == self.max_size

def is_empty(self):
return len(self.stack) == 0

def push(self, element):
if self.is_full():
print("Stack is full. Cannot push element.")
else:
self.stack.append(element)

def pop(self):
if self.is_empty():
print("Stack is empty. Cannot pop element.")
else:
return self.stack.pop()

def peek(self):
if self.is_empty():
print("Stack is empty. Cannot peek.")
else:
return self.stack[-1]

def size(self):
return len(self.stack)

Step 2: Create a Stack Object

stack = Stack(5)

Step 3: Use the Stack Class

stack.push(1)
stack.push(2)
stack.push(3)

print("Stack size:", stack.size())
print("Top element:", stack.peek())

print("Popped element:", stack.pop())
print("Stack size:", stack.size())

Output

Stack size: 3
Top element: 3
Popped element: 3
Stack size: 2

Implementing a Stack with a Custom Data Structure

If you want to implement a stack using a custom data structure, you can use a list or a tuple. Here’s an example using a list:

class Stack:
def __init__(self):
self.stack = []

def is_full(self):
return len(self.stack) == 0

def is_empty(self):
return len(self.stack) == 0

def push(self, element):
self.stack.append(element)

def pop(self):
if self.is_empty():
print("Stack is empty. Cannot pop element.")
else:
return self.stack.pop()

def peek(self):
if self.is_empty():
print("Stack is empty. Cannot peek.")
else:
return self.stack[-1]

def size(self):
return len(self.stack)

stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)

print("Stack size:", stack.size())
print("Top element:", stack.peek())

print("Popped element:", stack.pop())
print("Stack size:", stack.size())

Output

Stack size: 3
Top element: 3
Popped element: 3
Stack size: 2

Implementing a Stack with a Custom Data Structure (Tuple)

If you want to implement a stack using a tuple, you can use the following code:

class Stack:
def __init__(self):
self.stack = []

def is_full(self):
return len(self.stack) == 0

def is_empty(self):
return len(self.stack) == 0

def push(self, element):
self.stack.append(element)

def pop(self):
if self.is_empty():
print("Stack is empty. Cannot pop element.")
else:
return self.stack.pop()

def peek(self):
if self.is_empty():
print("Stack is empty. Cannot peek.")
else:
return self.stack[-1]

def size(self):
return len(self.stack)

stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)

print("Stack size:", stack.size())
print("Top element:", stack.peek())

print("Popped element:", stack.pop())
print("Stack size:", stack.size())

Output

Stack size: 3
Top element: 3
Popped element: 3
Stack size: 2

Conclusion

Implementing a stack in Python is a straightforward process that involves defining a custom data structure and implementing the necessary methods to support the basic operations. By using a list or a tuple, you can create a stack that supports the LIFO principle. This article has covered the basics of implementing a stack in Python, including the data structures, methods, and examples. With this knowledge, you can create your own stack data structures and use them in your Python programs.

Unlock the Future: Watch Our Essential Tech Videos!


Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top