How To Create A Stack In Python

5 min read

A stack in Python is a linear data structure that follows the Last In, First Out principle, meaning the most recently added item is the first one removed. Learning how to create a stack in Python is important because stacks are used in function call management, undo features, expression evaluation, browser history, syntax checking, and many algorithmic problems Nothing fancy..

In Python, a stack can be created in several ways, including using a built-in list, the deque class from the collections module, the LifoQueue class from the queue module, or by defining a custom class. Each method has advantages depending on whether you need simplicity, performance, thread safety, or object-oriented structure Nothing fancy..

What Is a Stack?

A stack is a collection where items are added and removed from the same end. This end is commonly called the top of the stack The details matter here. Still holds up..

The two most important stack operations are:

  • Push: Add an item to the top of the stack.
  • Pop: Remove and return the top item from the stack.

Additional useful operations include:

  • Peek or top: View the top item without removing it.
  • is_empty: Check whether the stack has no items.
  • size: Get the number of items in the stack.

A stack works according to the LIFO, or Last In, First Out, rule And it works..

For example:

Push 10
Stack: [10]

Push 20
Stack: [10, 20]

Push 30
Stack: [10, 20, 30]

Pop
Returns: 30
Stack: [10, 20]

The last item pushed, 30, is the first one popped Small thing, real impact..

Creating a Stack Using a Python List

The simplest way to create a stack in Python is by using a built-in list.

Python lists already support many stack operations:

  • Use append() to push an item.
  • Use pop() to remove the last item.
  • Access the last item using indexing.
  • Check if the list is empty using if stack:.

Example:

stack = []

stack.append(10)
stack.append(20)
stack.append(30)

print(stack)

Output:

[10, 20, 30]

To pop the top item:

removed_item = stack.pop()

print(removed_item)
print(stack)

Output:

30
[10, 20]

To peek at the top item:

if stack:
    print(stack[-1])

Output:

20

To check if the stack is empty:

if not stack:
    print("Stack is empty")

To get the size of the stack:

print(len(stack))

A complete basic stack using a list might look like this:

stack = []

def push(item):
    stack.append(item)

def pop():
    if is_empty():
        raise IndexError("pop from empty stack")
    return stack.pop()

def peek():
    if is_empty():
        raise IndexError("peek from empty stack")
    return stack[-1]

def is_empty():
    return len(stack) == 0

def size():
    return len(stack)

push(10)
push(20)
push(30)

print(pop())
print(peek())
print(size())

Output:

30
20
2

Using a list is convenient because it requires no extra imports. Still, when building a stack as a formal data structure, it is often better to wrap list operations inside functions or a class so that invalid operations are handled consistently Which is the point..

No fluff here — just what actually works Simple, but easy to overlook..

Creating a Stack Using collections.deque

The deque, short for double-ended queue, is often a better choice than a list when you want stack behavior with efficient operations from both ends Turns out it matters..

A deque supports fast insertion and removal at both the left and right sides. For a stack, we usually add and remove items from the right side.

from collections import deque

stack = deque()

stack.append(10)
stack.append(20)
stack.append(30)

print(stack)

Output:

deque([10, 20, 30])

To push:

stack.append(40)

To pop:

removed_item = stack.pop()
print(removed_item)

Output:

40

To peek:

print(stack[-1])

Output:

40

To check if empty:

if not stack:
    print("Stack is empty")

A more complete deque stack can be written like this:

from collections import deque

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

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

    def pop(self):
        if self.is_empty():
            raise IndexError("pop from empty stack")
        return self.items.

    def peek(self):
        if self.is_empty():
            raise IndexError("peek from empty stack")
        return self.items[-1]

    def is_empty(self):
        return len(self.items) == 0

    def size(self):
        return len(self.items)

    def __str__(self):
        return str(list(self.items))

stack = Stack()

stack.push("A")
stack.push("B")
stack.push("C")

print(stack)
print(stack.pop())
print(stack.peek())

Output:

['A', 'B', 'C']
C
B

The deque approach is especially useful when you expect frequent push and pop operations, because it is implemented as a double-ended queue and avoids some overhead associated with list resizing.

Creating a Stack Using queue.LifoQueue

Python also provides the LifoQueue class from the built-in queue module. This class is designed for last-in, first-out behavior and is useful in multithreaded programs where thread safety matters.

Example:

from queue import LifoQueue

stack = LifoQueue()

stack.put(10)
stack.put(20)
stack.put(30)

print(stack.get())

Output:

30

The main methods are:

  • put(item) to push.
  • get() to pop.
  • empty() to check if the stack is empty.
  • qsize() to get the size.

Example:


```python
stack.put("A")
stack.put("B")
stack.put("C")

while not stack.empty():
    print(stack.get())

Output:

C
B
A

get() blocks when the queue is empty. For code that must not block, use get_nowait() and handle the resulting queue.Empty exception:

from queue import Empty, LifoQueue

stack = LifoQueue()
stack.put("A")

try:
    item = stack.get_nowait()
except Empty:
    print("Stack is empty")
else:
    print(item)

Because LifoQueue is thread-safe, it is a strong option when multiple threads need to access the same stack. Its operations are slower than equivalent list operations, so it is usually not necessary for single-threaded programs Simple, but easy to overlook..

Choosing an Implementation

Implementation Best for Main advantage Main limitation
list Simple, single-threaded stacks Easy to read and use Not thread-safe
collections.deque Frequent operations at either end Efficient and flexible Requires slightly more setup
queue.LifoQueue Multithreaded programs Thread-safe Operations may block

For most everyday use, a list or a small Stack class built on deque is sufficient. Choose LifoQueue when thread safety or blocking behavior is part of the program’s design.

Conclusion

A stack follows the last in, first out (LIFO) principle: the most recently added item is the first one removed. Still, python provides several suitable implementations. A list is the simplest option, collections.Now, deque offers efficient operations at both ends, and queue. LifoQueue adds thread safety for concurrent programs. By matching the implementation to the program’s requirements and encapsulating stack operations, you can write code that is clear, efficient, and reliable Most people skip this — try not to..

Just Went Live

New and Noteworthy

Others Liked

More Reads You'll Like

Thank you for reading about How To Create A Stack In Python. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home