Implementing a Stack in Python: Understanding the Basics

Mounika Gali
Women in Technology
4 min readSep 15, 2023

--

Imagine a stack of plates, a stack of coins, or a pile of books. When you add or remove an item, you almost always do it from the top. This is essentially what a “stack” data structure is in computer science. It’s a way of organizing and managing data where you work with items at one end, known as the “top.”

What Is a Stack?

In more technical terms, a stack is an ordered collection of items where you can add new items or remove existing ones, but you can only do this at the same end, which is usually referred to as the “top.” It is a linear data structure i.e it can be thought of as having two ends : ‘top’ and ‘bottom’.

The LIFO Principle

One of the key characteristics of a stack is its behavior known as “LIFO,” which stands for “Last In First Out.” This means that the item you most recently added to the stack will be the first one to be removed. It’s similar to a stack of trays; the last tray you put on top is the first one you take off when you need one.

Real-World Applications

You might be wondering, “Why do we need stacks in programming?” Well, stacks have many practical applications. Let’s take a look at one common example:

Every web browser has a back button, right?

As you navigate from one web page to another, those pages are placed on a stack. Think of it as putting the URLs on a virtual stack. The page you’re currently viewing is on the top of the stack, and the first page you looked at is at the bottom.

Now, here’s where the stack concept becomes handy. When you click on the browser’s back button, you move through those pages in reverse order — just like taking plates off a stack. The page you were last on (the top of the stack) is the first one you’ll go back to. This behavior allows you to backtrack through the web pages you’ve visited in the order you visited them.

Implementing a Stack in Python

Now that we understand what a stack is and why it’s useful, let’s dive into implementing a basic stack in Python.

Implementation of a stack in Python, or any object-oriented programming language, can be done by creating a class. Stack operations such as push(), pop() and peek() can be implemented as methods using lists.

class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return len(self.items) == 0
def push(self, item):
self.items.append(item)
def pop(self):
if not self.is_empty():
return self.items.pop()
def peek(self):
if not self.is_empty():
return self.items[-1]
def size(self):
return len(self.items)
  • We start by defining a Stack class.
  • The __init__ method initializes an empty list to store our stack's items.
  • is_empty checks if the stack is empty.
  • push adds an item to the top of the stack.
  • pop removes and returns the top item from the stack.
  • peek returns the top item without removing it.
  • size returns the number of items in the stack.

Do remember that nothing happens yet when we click the run button. We defined the attributes of an object within Stack class but we must create a Stack object and then use it. Below is an example : After the 3 push operations, our stack would contain 4, c, x. Then, the pop operation is performed, which removes the last added item i.e ‘x’. The final peek operation returns the top item from the stack, ‘c’.

s = Stack()

s.push(4)
s.push('c')
s.push('x')
s.pop()
s.peek()

With this simple Python implementation, you can create and manipulate stacks to solve various problems in computer science and beyond.

In conclusion, a stack is like a real-world stack of items, and it follows the LIFO principle. Understanding how stacks work is essential in programming, and we’ve implemented a basic stack in Python to help you get started with this fundamental data structure. Whether you’re building a web browser or solving other complex problems, the stack will be your reliable friend in the world of programming.

--

--