The simplest way to implement a stack in Python is a plain list: append() pushes onto the top and pop() removes the top item, both in amortised O(1) time. A stack is last in, first out (LIFO), so the most recently added item leaves first. For thread-safe or bounded stacks, collections.deque and queue.LifoQueue are the standard options.
This guide shows the list-based stack, a small typed class, the deque alternative, a thread-safe version, and a real use case: checking balanced brackets.
Python lists add and remove at the end in constant time, which matches stack behaviour exactly.
Calling pop() on an empty list raises IndexError, so test if stack: first when emptiness is possible. Do not use insert(0, x) and pop(0) for a stack; they work at the front of the list and cost O(n).
A class gives you a clear, restricted interface, so callers cannot accidentally index into the middle.
On Python 3.12 and newer you can write class Stack[T]: and omit TypeVar and Generic.
deque supports O(1) append() and pop() at the right end, and unlike a list it never needs to resize a large block of memory. Its maxlen argument makes a bounded stack that drops the oldest item when full, which is handy for undo history.
For ordinary stacks a list is just as fast and simpler. Choose deque when you want maxlen or when you also need fast operations at the other end.
Lists and deques do not let a consumer block until an item arrives. queue.LifoQueue is a locked, blocking stack made for threads.
Use get_nowait() with a queue.Empty handler when you cannot block. In asyncio code, use asyncio.LifoQueue instead.
Stacks appear wherever the most recent unfinished thing must be resolved first: parsing, undo, depth-first search, and function calls. This checker pushes every opening bracket and pops on each closing one.
It runs in O(n) time and uses O(n) extra space in the worst case.
No dedicated stack class exists for ordinary code. The built-in list is the idiomatic stack, with queue.LifoQueue for threaded programs.
Both give O(1) push and pop at the end, and the difference is negligible for most programs. Pick deque for bounded stacks with maxlen, otherwise use a list.
Use stack[-1] on a list or deque. Guard it with if stack: because indexing an empty list raises IndexError.
A stack removes the newest item first (LIFO), a queue removes the oldest item first (FIFO). In Python, a list handles stacks well, while queues should use collections.deque.
Implement a Python stack with a list, using append() to push and pop() to remove the top item, both in constant time. Wrap it in a small typed class for a clean interface, use deque(maxlen=n) for bounded history, and use queue.LifoQueue when several threads share the stack.