Implementing a Stack in Python

Real Python · Beginner ·💻 AI-Assisted Coding ·6y ago

Key Takeaways

Implementing a stack in Python using lists and collections.deque, with a focus on last-in-first-out performance and efficiency.

Full Transcript

so how do you go about actually implementing a stack in Python well that's what I'm going to cover in this lesson and luckily there are some great implementations that exist in Python already without you having to do any hard work to make them have this last in first out performance that you would want them to have if you wanted a stack data structure so the three different implementations that I'm going to cover in this course are list collections deck and qfo Q and in this video I'm gonna go through in the terminal and run you through how to use lists and collections deck we'll talk about life oq in the next video so the first and simplest way to implement a stack in Python is to just use a list so I'll say stack equals just an empty list and list has inbuilt functions which are essentially the same as push and pop and the first of these is append and so you can append one it's to append two and to append three and you can take a look so you have a stack and this is just the order that they were put in 1 2 & 3 but the 3 as you'll know from the last in first out ordering will be the first thing to get popped so stacked up pop and indeed it returns 3 to 1 and then again you get an error when you pop from an empty list so this is really really simple and it works really quite well in most cases but it's not the fastest possible implementation because under the hood a list needs to support indexing so for example if I say for I and range 10 and then I add them all to my stack stacked on append I then I'll have a stack with these four elements but I can get access to those elements really easily just by doing something like this and this takes very little time this operation but it does take a little extra overhead to support operations like these on a list and that manifests itself when sometimes you have to resize the amount of memory that's taken up by a list in order to accommodate new entry and sometimes that can be a little slower so a faster implementation is collections deck and so you have to import that from the collections module and then we can just say stack equals deck and this has essentially exactly the same the same usage as the list implementation so you say stacked on a pen and then stacked up pop and deck also has a pop left and you can use that to implement a queue but that's for another video series so you can just do stacked up pop and you can see has exactly the same behavior and then it just says pop from an empty deck when you try to pop from an empty deck exactly so again I'll just do to show you real quick and you can take a look at your stack and it's a deck with this information and again nine will be on the top so you can do the same thing the same little trick here and you say while stack stack dot pop or I'll say print stack top and again there popped in last in first out order so those are two really simple and easy ways to implement a stack in Python deck is a little bit faster but then again it doesn't offer the same indexing capability that the list implementation does or at least the indexing isn't quite as fast because the deck is implanted under the hood as a doubly linked list which gives it faster adding performance you can append elements faster and then a list is implemented as a resizable array under the hood if you're interested in things like that so it takes sometimes can take a little bit more time to add entries to the end of a list so if you really need pure speed deck is probably the better way to go

Original Description

You’ll see how to implement a stack in Python. There are some great implementations that exist already, so you don’t have to do all the hard work! You’ll start by learning about list and collections.deque. Click here to learn more: https://realpython.com/courses/python-stack/
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Real Python · Real Python · 0 of 60

← Previous Next →
1 A better Python REPL – bpython vs python interpreter
A better Python REPL – bpython vs python interpreter
Real Python
2 Introducing large-type.com – A Utility Website
Introducing large-type.com – A Utility Website
Real Python
3 Reading Hacker News Without Wasting Tons of Time
Reading Hacker News Without Wasting Tons of Time
Real Python
4 Forward References and Python 3 Type Hints
Forward References and Python 3 Type Hints
Real Python
5 Using Sublime Text as your Git Editor
Using Sublime Text as your Git Editor
Real Python
6 Python Code Linting and Auto-Complete for Sublime Text
Python Code Linting and Auto-Complete for Sublime Text
Real Python
7 Make your Python Code More Readable with Custom Exceptions
Make your Python Code More Readable with Custom Exceptions
Real Python
8 Write Better Tests with Sublime Text's Split Layout Feature
Write Better Tests with Sublime Text's Split Layout Feature
Real Python
9 How to Use Sublime Text from the Command Line
How to Use Sublime Text from the Command Line
Real Python
10 Rename Variables with Multiple Selection in Sublime Text
Rename Variables with Multiple Selection in Sublime Text
Real Python
11 Sublime Text Settings for Writing PEP 8 Python
Sublime Text Settings for Writing PEP 8 Python
Real Python
12 Write Cleaner Python with Sublime Text's Indent Guides
Write Cleaner Python with Sublime Text's Indent Guides
Real Python
13 Sublime Text Whitespace Settings for Python Development
Sublime Text Whitespace Settings for Python Development
Real Python
14 Function Argument Unpacking in Python
Function Argument Unpacking in Python
Real Python
15 Python Code Review: Debugging and Refactoring "Conway's Game of Life" +  Automated Tests
Python Code Review: Debugging and Refactoring "Conway's Game of Life" + Automated Tests
Real Python
16 Using "get()" to Return a Default Value from a Python Dict
Using "get()" to Return a Default Value from a Python Dict
Real Python
17 A Python Shorthand for Swapping Two Variables
A Python Shorthand for Swapping Two Variables
Real Python
18 Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Real Python
19 Click & Jump to Test Failures from the Command Line (iTerm2)
Click & Jump to Test Failures from the Command Line (iTerm2)
Real Python
20 Setting up Sublime Text for Python Developers
Setting up Sublime Text for Python Developers
Real Python
21 Sublime Text + Python Guide Overview
Sublime Text + Python Guide Overview
Real Python
22 Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Real Python
23 Type-Checking Python Programs With Type Hints and mypy
Type-Checking Python Programs With Type Hints and mypy
Real Python
24 A Shorthand for Merging Dictionaries in Python 3.5+
A Shorthand for Merging Dictionaries in Python 3.5+
Real Python
25 Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Real Python
26 My Python Code Looks Ugly and Confusing – Help!
My Python Code Looks Ugly and Confusing – Help!
Real Python
27 Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Real Python
28 Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Real Python
29 Programmer Portfolio – Example and Walkthrough
Programmer Portfolio – Example and Walkthrough
Real Python
30 How to Get Your 1st Speaking Gig at a Tech Conference
How to Get Your 1st Speaking Gig at a Tech Conference
Real Python
31 How to Build Your Public Speaking Skills as a Developer
How to Build Your Public Speaking Skills as a Developer
Real Python
32 The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
Real Python
33 Setting up Sublime Text for Python Developers – Lesson #1
Setting up Sublime Text for Python Developers – Lesson #1
Real Python
34 Cool New Features in Python 3.6
Cool New Features in Python 3.6
Real Python
35 "is" vs "==" in Python – What's the Difference? (And When to Use Each)
"is" vs "==" in Python – What's the Difference? (And When to Use Each)
Real Python
36 Emulating switch/case Statements in Python with Dictionaries
Emulating switch/case Statements in Python with Dictionaries
Real Python
37 Python Function Argument Unpacking Tutorial (* and ** Operators)
Python Function Argument Unpacking Tutorial (* and ** Operators)
Real Python
38 What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
Real Python
39 A Crazy Python Dictionary Expression ?!
A Crazy Python Dictionary Expression ?!
Real Python
40 String Conversion in Python: When to Use __repr__ vs __str__
String Conversion in Python: When to Use __repr__ vs __str__
Real Python
41 Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Real Python
42 Optional Arguments in Python With *args and **kwargs
Optional Arguments in Python With *args and **kwargs
Real Python
43 Python Context Managers and the "with" Statement (__enter__ & __exit__)
Python Context Managers and the "with" Statement (__enter__ & __exit__)
Real Python
44 Installing Python Packages with pip and virtualenv / venv
Installing Python Packages with pip and virtualenv / venv
Real Python
45 "For Each" Loops in Python with enumerate() and range()
"For Each" Loops in Python with enumerate() and range()
Real Python
46 Python Code Review: LibreOffice Automation and the Python Standard Library
Python Code Review: LibreOffice Automation and the Python Standard Library
Real Python
47 Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Real Python
48 Python Tutorial: List Comprehensions Step-By-Step
Python Tutorial: List Comprehensions Step-By-Step
Real Python
49 Leveraging Python's Implicit "return None" Statements
Leveraging Python's Implicit "return None" Statements
Real Python
50 What's the meaning of underscores (_ & __) in Python variable names?
What's the meaning of underscores (_ & __) in Python variable names?
Real Python
51 Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Real Python
52 Writing automated tests for Python command-line apps and scripts
Writing automated tests for Python command-line apps and scripts
Real Python
53 How to find great Python packages on PyPI, the Python Package Repository
How to find great Python packages on PyPI, the Python Package Repository
Real Python
54 Immutable vs Mutable Objects in Python
Immutable vs Mutable Objects in Python
Real Python
55 PyPI vs Warehouse, the Next-Generation Python Package Repository
PyPI vs Warehouse, the Next-Generation Python Package Repository
Real Python
56 pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
Real Python
57 My Experience at PyCon 2017 in Portland
My Experience at PyCon 2017 in Portland
Real Python
58 Pylint Tutorial – How to Write Clean Python
Pylint Tutorial – How to Write Clean Python
Real Python
59 "Reverse a List in Python" Tutorial: Three Methods & How-to Demos
"Reverse a List in Python" Tutorial: Three Methods & How-to Demos
Real Python
60 Python Refactoring: "while True" Infinite Loops & The "input" Function
Python Refactoring: "while True" Infinite Loops & The "input" Function
Real Python

Learn how to implement a stack in Python using lists and collections.deque, and understand the trade-offs between these two data structures in terms of efficiency and functionality.

Key Takeaways
  1. Import the collections module
  2. Create an empty list or collections.deque to serve as a stack
  3. Use the append method to add elements to the stack
  4. Use the pop method to remove elements from the stack
  5. Compare the performance of lists and collections.deque for stack implementation
💡 Collections.deque is generally faster than lists for stack implementation due to its doubly linked list implementation, but lists offer faster indexing capabilities.

Related Reads

📰
Why Your AI Assistant Needs a Dumb Pre-Pass
Learn why a simple pre-pass can improve AI assistant performance in code review by filtering out basic errors
Dev.to · CopperSunDev
📰
Nobody told junior developers this was going to happen. But here we are. 👇
The software industry has changed with AI taking over repetitive work, affecting junior developer job prospects
Dev.to · Johan Cruz
📰
I Kept Losing My Best AI Prompts, So I Built PromptTrace
Learn how to organize and track AI prompts with PromptTrace, a tool built to solve the problem of losing valuable prompts
Medium · Programming
📰
Neuro-Synthetix: a voice bridge from a village to the world's clinical trials
Learn how Neuro-Synthetix bridges the gap between village patients and global clinical trials using AI-powered voice technology
Dev.to · Shadrak
Up next
Anthropic Building a Lovable Competitor?
Growth Learner
Watch →