How To Implement A Python Stack - Real Python

Table of Contents

  • What Is a Stack?
  • Implementing a Python Stack
    • Using list to Create a Python Stack
    • Using collections.deque to Create a Python Stack
  • Python Stacks and Threading
  • Python Stacks: Which Implementation Should You Use?
  • Conclusion
Remove ads

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Implementing a Stack in Python

Have you heard of stacks and wondered what they are? Do you have the general idea but are wondering how to implement a Python stack? You’ve come to the right place!

In this tutorial, you’ll learn:

  • How to recognize when a stack is a good choice for data structures
  • How to decide which implementation is best for your program
  • What extra considerations to make about stacks in a threading or multiprocessing environment

This tutorial is for Pythonistas who are comfortable running scripts, know what a list is and how to use it, and are wondering how to implement Python stacks.

Free Bonus: Click here to get a Python Cheat Sheet and learn the basics of Python 3, like working with data types, dictionaries, lists, and Python functions.

What Is a Stack?

A stack is a data structure that stores items in an Last-In/First-Out manner. This is frequently referred to as LIFO. This is in contrast to a queue, which stores items in a First-In/First-Out (FIFO) manner.

It’s probably easiest to understand a stack if you think of a use case you’re likely familiar with: the Undo feature in your editor.

Let’s imagine you’re editing a Python file so we can look at some of the operations you perform. First, you add a new function. This adds a new item to the undo stack:

Pushing the "add function" operation to the undo stack.

You can see that the stack now has an Add Function operation on it. After adding the function, you delete a word from a comment. This also gets added to the undo stack:

Pushing the "delete word" operation on the undo stack.

Notice how the Delete Word item is placed on top of the stack. Finally you indent a comment so that it’s lined up properly:

Pushing the "indent comment" operation on the undo stack.

You can see that each of these commands are stored in an undo stack, with each new command being put at the top. When you’re working with stacks, adding new items like this is called push.

Now you’ve decided to undo all three of those changes, so you hit the undo command. It takes the item at the top of the stack, which was indenting the comment, and removes that from the stack:

Popping the "indent comment" function from the undo stack.

Your editor undoes the indent, and the undo stack now contains two items. This operation is the opposite of push and is commonly called pop.

When you hit undo again, the next item is popped off the stack:

Popping the "delete word" operation from the undo stack.

This removes the Delete Word item, leaving only one operation on the stack.

Finally, if you hit Undo a third time, then the last item will be popped off the stack:

Popping the "add function" operation from the undo stack.

The undo stack is now empty. Hitting Undo again after this will have no effect because your undo stack is empty, at least in most editors. You’ll see what happens when you call .pop() on an empty stack in the implementation descriptions below.

Remove ads

Implementing a Python Stack

There are a couple of options when you’re implementing a Python stack. This article won’t cover all of them, just the basic ones that will meet almost all of your needs. You’ll focus on using data structures that are part of the Python library, rather than writing your own or using third-party packages.

You’ll look at the following Python stack implementations:

  • list
  • collections.deque
  • queue.LifoQueue

Using list to Create a Python Stack

The built-in list structure that you likely use frequently in your programs can be used as a stack. Instead of .push(), you can use .append() to add new elements to the top of your stack, while .pop() removes the elements in the LIFO order:

Python >>> myStack = [] >>> myStack.append('a') >>> myStack.append('b') >>> myStack.append('c') >>> myStack ['a', 'b', 'c'] >>> myStack.pop() 'c' >>> myStack.pop() 'b' >>> myStack.pop() 'a' >>> myStack.pop() Traceback (most recent call last): File "<console>", line 1, in <module> IndexError: pop from empty list

Tag » How Many Stacks Is 1000 Blocks