Python Stack: How to Use Lists and Deques

When you are adding last-in, first-out processing to a Python program, you need a container that keeps the newest item at the top. A list or deque can serve as a stack when you add and remove items at the same end.

This article explains how to create a stack with a list and what happens when you pop an empty list or deque.

TL;DR: Python Stack

A Python stack is a last-in, first-out (LIFO) way to manage items, and a list with append and pop is a direct implementation for ordinary single-threaded code.

  • Push with stack.append(item) and remove the newest item with stack.pop().
  • Check if stack before peeking at stack[-1], or handle IndexError from an empty pop.
  • Choose collections.deque for frequent operations at either end, and queue.LifoQueue when threads must coordinate through a synchronized queue.

What Is a Python Stack?

A stack describes the order in which items are handled: the last item added is the first one removed. Python provides flexible containers rather than a built-in class named Stack. Your code chooses a container and follows the LIFO rule.

A pile of tasks illustrates the order: add a task on top, then take it back before older work. A list can also be indexed or sliced, but the stack interface restricts operations to its top.

A push adds an item to the top. Pop removes it and returns its value. Peek reads without removal.

Lists have no push or peek method. Use append for push and index -1 for peek after checking for an item.

Stack ideaPython list operationEffect
Pushappend(item)Adds at the top, the right end
Poppop()Removes and returns the rightmost item
Peekstack[-1]Reads the top and leaves it in place
Empty checkif not stackTests whether there are items to read

Python’s data structures tutorial demonstrates a list as a stack. The pop operation removes the final list item by default.

How to Use a Python Stack Step by Step

Build a stack by starting with an empty list, appending each new item, and popping when the latest item should be handled. I use a list for this short task history because its right-end operations express the LIFO rule directly.

Step 1: Create the stack and push items

An empty list is a valid starting stack. Each call to append places the new item at the top, so the newest task appears at the right edge when Python displays the list.

from collections import deque

stack = []
for task in ("read", "edit", "save"):
    stack.append(task)
    print("push:", task, "| stack:", stack)

print("next undo:", stack.pop())
print("remaining:", stack)

work = deque(("read", "edit", "save"))
print("deque top:", work.pop())
print("deque remaining:", work)

Run this saved example with python3 stack_walkthrough.py. Its complete output is:

push: read | stack: ['read']
push: edit | stack: ['read', 'edit']
push: save | stack: ['read', 'edit', 'save']
next undo: save
remaining: ['read', 'edit']
deque top: save
deque remaining: deque(['read', 'edit'])
Terminal output showing list and deque stack pushes and pops
The list and deque show each push and the returned top item

Both containers return save first, leaving read and edit behind. The deque spelling names the container type in its display. Its stack behavior matches the list.

Step 2: Peek at the top without removing it

Use index -1 to read the newest list item without removing it. A negative index counts from the end of the sequence and provides a direct peek at the stack top.

stack = ["read", "edit", "save"]
if stack:
    print("top:", stack[-1])
    print("still present:", stack)
else:
    print("stack is empty")

The guard prevents indexing an empty list. This lookup leaves the list unchanged, so the next operation sees the same top item.

Step 3: Remove items in LIFO order

Call pop without an index to remove the top and receive its value. The returned item can then be processed or passed to another function.

stack = ["read", "edit", "save"]
while stack:
    task = stack.pop()
    print("handle:", task, "| remaining:", stack)

This loop stops when the list becomes empty, and each iteration removes one item from the right. Use this form when every stacked item should be handled and there is no need to preserve the original sequence.

Empty Stacks and Choosing a Container

Popping an empty stack raises IndexError. I check emptiness before peeking, and guard repeated removals with a truth test.

Handle an empty pop

I ran the empty case directly because a first stack often begins with no items. The captured output shows the exception class and message for both list and deque.

from collections import deque

try:
    [].pop()
except IndexError as error:
    print(type(error).__name__ + ":", error)

try:
    deque().pop()
except IndexError as error:
    print(type(error).__name__ + ":", error)

Run python3 empty_stack_case.py. The observed output is:

IndexError: pop from empty list
IndexError: pop from an empty deque
Terminal output showing IndexError from popping an empty list and deque
Empty containers raise IndexError when popped

The messages differ, but both failures mean there is no item to remove. Test if stack before removal when empty is a normal state, or catch IndexError when the operation should decide whether an item exists.

Choose list, deque, or LifoQueue

A list is a direct choice for a single-threaded stack. A deque supports operations at the right end and efficient appends and pops at either end. The queue.LifoQueue type adds synchronization for threaded communication.

ContainerUse it whenTop operationsWatch for
listA straightforward local stack is enoughappend(), pop(), stack[-1]Empty pop or peek needs a guard
collections.dequeYou need stack behavior plus frequent work at either endappend(), pop(), stack[-1]It is not a general replacement for list slicing or middle indexing
queue.LifoQueueThreads exchange work through a synchronized LIFO queueput(), get()A blocking get() waits for an item unless configured otherwise

Python’s collections.deque documentation describes efficient appends and pops at both ends. Both list and deque support right-end stack operations. Choose deque when left-end operations also matter, and see AskPython’s list vs deque comparison for a wider comparison.

Stack and queue access orders differ. A stack uses one end, while a first-in, first-out queue removes the oldest item at the opposite end. The example prints those results without measuring elapsed performance.

from collections import deque

stack = list(range(4))
queue = deque(range(4))
print("list stack top:", stack.pop())
print("deque stack top:", queue.pop())
print("list FIFO removal:", stack.pop(0))
print("deque FIFO removal:", queue.popleft())
print("remaining list:", stack)
print("remaining deque:", list(queue))

Run python3 ends_comparison.py. The output is:

list stack top: 3
deque stack top: 3
list FIFO removal: 0
deque FIFO removal: 0
remaining list: [1, 2]
remaining deque: [1, 2]
Terminal output comparing stack pops and FIFO removals from list and deque
Right-end stack pops return the newest item. left-end removals return the oldest

Both right-end pops return 3, while the left-end removals return 0. Python’s data structures tutorial notes that removing the first item from a list shifts the remaining items. Use deque.popleft() for ongoing FIFO work instead of repeatedly calling list.pop(0).

queue.LifoQueue serves a different need from a plain list: its methods coordinate access among threads. The Python queue documentation describes synchronized queues for multi-producer and multi-consumer programs. A bounded queue can block a producer when full, and a default blocking get() waits when no item is available, so it is usually unnecessary for a local stack.

Where stacks are useful

A stack fits tasks whose newest unfinished action should be handled first. That rule appears in undo histories, depth-first traversal, expression parsing, and backtracking through choices.

An undo history can append each completed action and pop the latest action to reverse it. A depth-first traversal can push neighboring nodes, then pop one node to continue along the latest branch. A parser can push opening delimiters and pop when it sees their matching closing delimiters, reporting a mismatch when the top does not match.

Python functions also use a call stack to track active calls, but that runtime mechanism is distinct from a list that your program explicitly uses as a data structure. For recursive code and its depth limits, see the AskPython guide to Python recursion.

Python documents right-end list and deque operations as efficient and approximately constant-time. A stack does not make arbitrary search constant-time. Search and middle access depend on the container and may require scanning.

Common Errors and Next Steps

The boundary case is removal when no item is available. A truth check handles it when an empty container is an expected state.

CaseSymptomFix
Peek at an empty listIndexError from index -1Check if stack before reading the top
Pop an empty list or dequeIndexError: pop from empty list, or IndexError: pop from an empty dequeCheck for an item first, or catch IndexError
Use list as a FIFO queueRemoving the first item shifts remaining list itemsUse deque.popleft() for ongoing FIFO work

For concurrent producers and consumers, use queue.LifoQueue and account for blocking get behavior. For ordinary stack operations, keep adding and removing at the same end.

Conclusion

A Python stack is a usage rule rather than a dedicated built-in type: add at one end and remove from that same end to get LIFO behavior. Start with a list and its append() and pop() methods, check for emptiness before peeking, and switch to deque or LifoQueue only when their specific behavior fits.

FAQ

These quick answers cover the common questions about Python’s stack behavior.

Does Python have a built-in Stack type?

Python does not provide a standard built-in class named Stack. Use a list or collections.deque with append() and pop() for LIFO behavior.

How do I check whether a Python stack is empty?

Use if not stack to test a list or deque. Check before peeking at stack[-1], or handle IndexError if you call pop() on an empty container.

Is a Python list the same as a stack?

A list is a general-purpose sequence. It acts as a stack when code adds and removes items at one end in last-in, first-out order.

Safa Mulani
Safa Mulani

An enthusiast in every forthcoming wonders!

Articles: 189