Sunday, November 1, 2026 New tutorials published every day
Home
Tutorials
Core PHP PHP Course JavaScript React & Next.js Python WordPress Artificial Intelligence
Free Tools
JSON Formatter Base64 Encoder / Decoder Password Generator Text to QR Code Generator Word Counter Case Converter Age Calculator Color Converter Number to Words All Free Tools
Projects
PHP Projects — all projects
Students
Course Registration Download Syllabus Verify Certificate Student Leaderboard
Resources
Search tutorials About CodingCush Contact
More
Login
Data Structures

Stack vs Queue: What Is the Difference? (With Examples)

Stack vs queue explained simply: LIFO vs FIFO, push and pop vs enqueue and dequeue, with plates, coffee queues and Python examples for interviews.

A stack and a queue are both simple ways of storing items in order, but they differ in one rule: a stack removes the last item you added (LIFO — Last In, First Out), while a queue removes the first item you added (FIFO — First In, First Out). A stack behaves like a pile of plates; a queue behaves like a line of people at a ticket counter.

What Is a Stack?

Imagine the plate pile in a kitchen. You place clean plates on top of each other, and when you need one, you take it from the top. You never pull a plate from the middle unless you enjoy washing the floor as well. That is a stack: new items go on top, and removals also happen at the top. The last plate you placed is the first one you take away — Last In, First Out.

A stack supports two main operations. Push adds an item to the top, and pop removes the item from the top. Most stacks also offer peek (or top), which lets you look at the top item without removing it — the programming equivalent of glancing at the pile before committing.

stack = []

stack.append("page A")   # push
stack.append("page B")   # push
stack.append("page C")   # push

print(stack.pop())       # page C  (last in, first out)
print(stack.pop())       # page B
print(stack)             # ['page A']

This is not a made-up classroom example: your browser's Back button works exactly like this. Every page you visit is pushed onto a history stack, and pressing Back pops the most recent page off. The Undo button in your editor, and the way programmes remember which function called which, use the same idea.

What Is a Queue?

Now picture the queue at a coffee shop. The first person who joined the line is served first, and new arrivals join at the back. Nobody (in a polite country, at least) cuts in at the front. That fairness rule — First In, First Out — is a queue. Adding an item is called enqueue and happens at the back; removing one is called dequeue and happens at the front.

from collections import deque

queue = deque()
queue.append("print job 1")   # enqueue at the back
queue.append("print job 2")
queue.append("print job 3")

print(queue.popleft())        # print job 1  (first in, first out)
print(queue.popleft())        # print job 2
print(queue)                  # deque(['print job 3'])

Queues quietly run much of the software you use daily. Printers work through documents in queue order. Websites place incoming requests in a queue so the server handles them fairly. Downloads, message apps and customer-support tickets all line up in queues. In Python, the official tutorial's Data Structures chapter shows both patterns — lists used as stacks, and queues built for first-in, first-out behaviour — in its Python documentation on data structures.

The official Python Tutorial Data Structures chapter on docs.python.org, whose contents list 'Using Lists as Stacks' and 'Using Lists as Queues'
The official Python Tutorial, Data Structures chapter — its contents list both "Using Lists as Stacks" and "Using Lists as Queues".

Stack vs Queue in One Table

Point Stack Queue
Rule LIFO — Last In, First Out FIFO — First In, First Out
Real-life picture A pile of plates A line at a ticket counter
Insert happens at The top (same end) The back (rear)
Remove happens at The top (same end) The front
Main operations push, pop, peek enqueue, dequeue, front
Everyday examples Browser Back button, Undo, function calls Print jobs, waiting requests, message lines

The single most important row is the first one. If an interviewer asks you nothing else, remember: same-end versus two-ends. A stack works at one end only; a queue works at both ends — in at the back, out at the front.

Why the Removal Cost Differs in Python

Here is a detail that separates a memorised answer from an understood one. In Python, using a list as a stack is fast, because append() and pop() work at the end of the list, where nothing else has to move. A queue built from a plain list is slow, though: removing the first item with pop(0) forces every remaining item to shuffle one place forward. Do that a million times and your programme develops a noticeable limp. That is why the example above uses deque from the collections module, which is built for fast additions and removals at both ends. MDN's reference for JavaScript's Array methods shows the same pattern in another language: push/pop for stack behaviour, and shift for queue behaviour (with the same cost warning in large arrays).

If you enjoyed this comparison, our guide to array vs linked list explains where these structures actually store their items in memory, and it pairs nicely with what you have just read.

A Famous Stack Trick: Checking Balanced Brackets

Here is the example that makes stacks click for most people. Suppose you must check whether the brackets in a line of code are balanced — every opening bracket closed in the right order, as in { [ ( ) ] }. A stack solves it beautifully: walk through the characters, push every opening bracket, and whenever a closing bracket appears, pop the top and check that the pair matches. If the stack is empty at the end, the brackets are balanced.

def is_balanced(text):
    pairs = {")": "(", "]": "[", "}": "{"}
    stack = []
    for ch in text:
        if ch in "([{":
            stack.append(ch)
        elif ch in ")]}":
            if not stack or stack.pop() != pairs[ch]:
                return False
    return len(stack) == 0

print(is_balanced("{ [ ( ) ] }"))   # True
print(is_balanced("{ [ ( ] ) }"))   # False

Notice why a queue would fail here: the closing bracket must match the most recent opener, not the oldest one — and "most recent first" is exactly the stack rule. The mirror-image classic for queues is breadth-first search, where you explore a tree or a map level by level, always visiting the place that has waited longest. Same family of ideas, opposite removal rule.

How Fast Are They? A Quick Big O Note

For interviews, one line about speed is usually enough: push, pop, enqueue and dequeue are all O(1) — constant time — when the structure is built properly, because each operation touches only one end and nothing else has to move. Looking at the top of a stack or the front of a queue is also O(1). Searching for an item inside either one is O(n), because you may have to look at every element — a polite way of saying these two structures are designed for order, not for searching.

Which One Should You Use?

Choose by asking one question: which item should come out next? If the answer is "the most recent one" — undo steps, backtracking through a maze, checking that brackets in code are balanced, reversing a word — you want a stack. If the answer is "the one that has waited longest" — tasks, requests, messages, print jobs, breadth-first search through a tree or a graph — you want a queue. When in doubt, picture the plates and the coffee line; the correct structure usually introduces itself.

Stacks and queues are also the friendly front door to bigger data-structure ideas. Our explainer on what a hash table is covers the other classic beginner structure, the one that trades ordering for lightning-fast lookups by name.

Frequently Asked Questions

What does LIFO and FIFO mean?

LIFO means Last In, First Out: the newest item leaves first, as in a stack. FIFO means First In, First Out: the oldest item leaves first, as in a queue. They are simply the two removal rules written as initials.

Is a stack or a queue used for the browser Back button?

A stack. Each page you visit is pushed on top, and Back pops the latest page off, which is why you retrace your steps in reverse order.

Can one structure act as the other?

Programmers can simulate a queue using two stacks, and vice versa — a favourite interview puzzle — but in everyday code you simply pick the structure whose removal rule matches your problem.

Which is faster, a stack or a queue?

Both are fast when built correctly: their main operations are O(1), constant time. Slowness only appears when you use the wrong tool, like removing from the front of a Python list instead of using a deque.

Conclusion

A stack takes from the top; a queue serves from the front. Plates versus people in a line, LIFO versus FIFO, push/pop versus enqueue/dequeue — once those pictures stick, you will never confuse the two again, in an interview or in real code.

Lavkush
Written by

Lavkush Super Admin

Lavkush Kumar is a software developer with over 6 years of experience turning ideas into websites and web applications. He holds a Master of Computer Applications (MCA) degree and enjoys building for the web, exploring new tools, and sharing what he learns along the way.

Through CodingCush, Lavkush creates easy-to-follow tutorials and practical guides to help students and beginners learn software development without feeling overwhelmed. His approach is simple: learn by doing, build real projects, and keep improving one step at a time.

Whether you’re just starting out or looking to sharpen your skills, CodingCush is all about making learning practical, beginner-friendly, and fun.

0 Comments

Leave a Comment