惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

G
Google Developers Blog
云风的 BLOG
云风的 BLOG
Google DeepMind News
Google DeepMind News
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
博客园 - 三生石上(FineUI控件)
V
Visual Studio Blog
爱范儿
爱范儿
宝玉的分享
宝玉的分享
人人都是产品经理
人人都是产品经理
大猫的无限游戏
大猫的无限游戏
博客园 - 聂微东
月光博客
月光博客
雷峰网
雷峰网
L
LangChain Blog
Stack Overflow Blog
Stack Overflow Blog
B
Blog RSS Feed
有赞技术团队
有赞技术团队
T
Tailwind CSS Blog
阮一峰的网络日志
阮一峰的网络日志
V
V2EX
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
C
Check Point Blog
N
Netflix TechBlog - Medium
罗磊的独立博客
博客园 - 司徒正美
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
F
Full Disclosure
Security Archives - TechRepublic
Security Archives - TechRepublic
V
Vulnerabilities – Threatpost
H
Help Net Security
博客园 - 【当耐特】
博客园_首页
Microsoft Security Blog
Microsoft Security Blog
小众软件
小众软件
Hugging Face - Blog
Hugging Face - Blog
L
Lohrmann on Cybersecurity
C
Cybersecurity and Infrastructure Security Agency CISA
P
Privacy International News Feed
Blog — PlanetScale
Blog — PlanetScale
C
CERT Recently Published Vulnerability Notes
P
Privacy & Cybersecurity Law Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
Cisco Talos Blog
Cisco Talos Blog
K
Kaspersky official blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Cyberwarzone
Cyberwarzone
S
Schneier on Security
S
SegmentFault 最新的问题
C
Cyber Attacks, Cyber Crime and Cyber Security
S
Securelist

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
How to use stacks in Python
Santiago Her · 2026-05-09 · via DEV Community

A stack is a linear data structure where inserted elements are kept in insertion order and only the last one to be added is removed, this is also known as LIFO (last in first out) behavior.

A traditional Stack supports three operations:

  • Insertion or push
  • Peek or top
  • Deletion or pop

Execution times for both operations can vary slightly depending on the implementation, all three can be executed in constant times O(1) with the right data structure.

Examples

Consider the following list of numbers, let's assume the last element in the list is the last one to be inserted:

stack = [1, 7, 5, 6, 5, 12, 4]

Enter fullscreen mode Exit fullscreen mode

The following operations will produce the following results and the list will behave like a stack:

stack = [1, 7, 5, 6, 5, 12, 4]
stack.pop() # Pop is a deletion operation and number 4 has been removed from the stack

print(stack[-1]) # 12 - This gives us the element at the top of the stack which is a peek operation

print(stack) # [1, 7, 5, 6, 5, 12]
stack.append(30) # Append is an insertion operation and adds an element at the end of the list
#Number 30 has been added

print(stack) # [1, 7, 5, 6, 5, 12, 30]

Enter fullscreen mode Exit fullscreen mode

Let's analyze another example:

stack = []
stack.append(1)
stack.append(2)
stack.append(3)
print(stack) # [1, 2, 3]
print(stack.pop()) # 3
print(stack.pop()) # 2
print(stack.pop()) # 1
print(stack) # []

Enter fullscreen mode Exit fullscreen mode

As you can see, printing the values that are removed from the stack will give us the list of elements in reverse order. This gives stacks some interesting applications we'll analyze later.

How to use stacks in Python

In the previous examples we used lists to represent stacks, however there are more ways to implement stacks that we should analyze:

Using lists

This is the approach we used in the examples. We just create a list and perform insert operations by appending elements to the end of the list.

stack = [3, 2, 5, 6]
print(stack.pop()) # 6
print(stack) # [3, 2, 5]

Enter fullscreen mode Exit fullscreen mode

This approach works well and many people use it, let's check how each operation performs using lists:

  • Insert: O(1) Amortized
  • Peek: O(1)
  • Delete: O(1)

The reason why the complexity of insert is O(1) amortized is because in the implementation of list, a new list is created if the list grows as big as the size of its internal array. However developers came up with a smart way to reduce the amount of times this has to be done, by doubling or greatly increasing the size of the new internal array. This means that an O(n) operation will be performed very few times turning the complexity of the insert operation by O(1) amortized.

If you want to understand why amortized O(1) works at a deeper level, read how dynamic arrays handle memory allocation, it's a topic worth its own article.

Using deques

This is my preferred approach as deques use linked lists underneath, which is the optimal way to implement stacks for time performance.

from collections import deque

stack = deque()

# Push items
stack.append(1)
stack.append(2)
stack.append(3)

# Pop item (last in, first out)
top = stack.pop()  # returns 3
print(top) # 3

# Peek at top without removing
top = stack[-1]  # returns 2
print(top) # 2

print(stack)  # deque([1, 2])

Enter fullscreen mode Exit fullscreen mode

Another example

from collections import deque

my_list = [3, 4, 5, 2]
stack = deque(my_list)

while stack:
    print(stack.pop()) # Prints 2, 5, 4, 3

Enter fullscreen mode Exit fullscreen mode

This is the performance of stack operations using deque in Python:

  • Insert: O(1)
  • Peek: O(1)
  • Delete: O(1)

The difference of using a list and a deque is going to be insignificant in most cases, however there might be some special applications and corner cases where using a deque might be needed. I can imagine there are LeetCode problems where using a deque (linked list) can make the difference between passing and not passing.

Creating your own Stack class

Most of the times it's unnecessary to create your own class to utilize stacks. You can do it if you want to solve some shortcomings that lists and deques have. For example deques and lists allow you to peek elements in the middle of the stack, add or delete elements in any position, in other words you can perform operations that a stack doesn't support. You can solve this by creating your own Stack class where you have more control over the operations that are allowed.

Example:

from collections import deque

class Stack:
    def __init__(self):
        self._stack = deque()

    def push(self, item):
        self._stack.append(item)

    def pop(self):
        if not self._stack:
            raise IndexError("Pop from empty stack")
        return self._stack.pop()

    def peek(self):
        if not self._stack:
            raise IndexError("Peek from empty stack")
        return self._stack[-1]

    def __repr__(self):
        return f"Stack({list(self._stack)})"

# Usage
stack = Stack()

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

print(stack)          # Stack([1, 2, 3])
print(stack.peek())   # 3
print(stack.pop())    # 3
print(stack.pop())    # 2
print(stack.pop())    # 1
print(stack.pop())    # IndexError: Pop from empty stack

Enter fullscreen mode Exit fullscreen mode

As this class uses a deque to represent the stack, its performance will be the same as the performance of a deque.

Applications

Stacks show up in real codebases and DSA problems. Here are some applications:

  • Parentheses matching
  • Tree traversals
  • DFS
  • Memento undo/redo

Parentheses matching

This is one of the simplest problems that can be solved using stacks. In summary what the algorithm does is to keep track of opening parentheses in a stack and as soon as you find a closing parenthesis you compare it to the one on top of the stack. Any inconsistencies mean that the parentheses are not valid.

Sample code solution for this problem: https://leetcode.com/problems/valid-parentheses/

from collections import deque


class Solution:
    def isValid(self, s: str) -> bool:
        closing_to_open = {')': '(', '}': '{', ']': '['}
        stack = deque()
        for c in s:
            if c in closing_to_open:
                if not stack or stack.pop() != closing_to_open[c]:
                    return False
            else:
                stack.append(c)
        return len(stack) == 0

Enter fullscreen mode Exit fullscreen mode

This same idea can also be used to match HTML opening and closing tags, JSON objects, XML tags etc. Matching parentheses is the simplest version of this problem but there are some variations to it.

Tree traversals

Traversing trees and graphs can be done in multiple ways, you can do it recursively or iteratively. Iterative traversals are usually more efficient but you'll need data structures like stacks or queues to traverse them. Traversing a tree or any kind of graph using stacks will result in a DFS type of traversal.
We can use stacks to perform some of the main binary tree traversals:

  • Pre-order
  • In-order
  • Post-order

The following code shows how to perform an inorder traversal of a binary tree using stacks:

from collections import deque


class Solution:
    def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        inorder = []
        stack = deque()
        node = root
        while node or stack:
            while node:
                stack.append(node)
                node = node.left
            node = stack.pop()
            inorder.append(node.val)
            node = node.right
        return inorder

Enter fullscreen mode Exit fullscreen mode

This is a solution to the following problem: https://leetcode.com/problems/binary-tree-inorder-traversal/

DFS on graphs

We just saw how to perform a DFS on a tree, the same traversal can be performed on graphs. Have a look at the following problem: https://leetcode.com/problems/number-of-islands/
We are given a graph and we need to find how many connected components the graph has. This problem can be solved by performing a DFS or BFS search:

class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        for i in range(len(grid)):
            grid[i] = ["0"] + grid[i] + ["0"]
        waterRow = ["0"] * len(grid[0])
        grid = [waterRow] + grid
        grid.append(waterRow)
        moves = [(1, 0), (0, 1), (-1, 0), (0, -1)]
        visited = set()
        islands = 0
        for i in range(1, len(grid) - 1):
            for j in range(1, len(grid[i]) - 1):
                if grid[i][j] == "1" and (i, j) not in visited:
                    islands += 1
                    stack = collections.deque()
                    stack.append((i, j))
                    visited.add((i, j))
                    while stack:
                        pos =  stack.pop()
                        for m in moves:
                            newPos = (pos[0] + m[0], pos[1] + m[1])
                            if grid[newPos[0]][newPos[1]] == "1" and newPos not in visited:
                                visited.add(newPos)
                                stack.append(newPos)
        return islands

Enter fullscreen mode Exit fullscreen mode

Note: There's something funny about this solution and it is that I initially solved it using BFS with queue instead of using DFS. To turn it into DFS, all I had to do was to use a stack instead of a queue and the solution will still work. There are many problems that can be solved with both BFS or DFS without making any difference. I recommend you check articles about BFS and queues if you want to learn more about it.

Undo and redo functions

This is one of the most interesting applications of stacks. You can implement undo and redo functions using the Memento design pattern but I'll show a simplified example of it using stacks. A classic Memento implementation will use stacks too.

The following example shows the code of a TextEditor class that implements redo and undo functions using stacks:

from collections import deque

class TextEditor:
    def __init__(self):
        self.content = ""
        self._history = deque()
        self._future = deque()

    def type(self, text):
        self._history.append(self.content)
        self._future.clear()
        self.content += text

    def undo(self):
        if not self._history: return
        self._future.append(self.content)
        self.content = self._history.pop()

    def redo(self):
        if not self._future: return
        self._history.append(self.content)
        self.content = self._future.pop()

editor = TextEditor()
editor.type("Hello")
print(editor.content) # Hello
editor.type(" world")
print(editor.content) # Hello world
editor.undo()
print(editor.content) # Hello
editor.redo()
print(editor.content) # Hello world

Enter fullscreen mode Exit fullscreen mode

Conclusion

The stack is a fundamental linear data structure that has many useful applications. Knowing the situations where stacks are needed to solve problems is going to bring a lot of value for you as a developer, especially in DSA problems. If you want to continue studying data structures and algorithms I'd recommend you study its FIFO counterpart the queue, trees and graph algorithms like DFS and BFS.
If you have any questions or want to discuss anything please leave a comment in the comment section.