I corrected a few problems below. Also, a 'stack', in abstract programming terms, is usually a collection where you add and remove from the top, but the way you implemented it, you're adding to the top and removing from the bottom, which makes it a queue.

class myStack:
     def __init__(self):
         self.container = []  # You don't want to assign [] to self - when you do that, you're just assigning to a new local variable called `self`.  You want your stack to *have* a list, not *be* a list.

     def isEmpty(self):
         return self.size() == 0   # While there's nothing wrong with self.container == [], there is a builtin function for that purpose, so we may as well use it.  And while we're at it, it's often nice to use your own internal functions, so behavior is more consistent.

     def push(self, item):
         self.container.append(item)  # appending to the *container*, not the instance itself.

     def pop(self):
         return self.container.pop()  # pop from the container, this was fixed from the old version which was wrong

     def peek(self):
         if self.isEmpty():
             raise Exception("Stack empty!")
         return self.container[-1]  # View element at top of the stack

     def size(self):
         return len(self.container)  # length of the container

     def show(self):
         return self.container  # display the entire stack as list


s = myStack()
s.push('1')
s.push('2')
print(s.pop())
print(s.show())
Answer from Brionius on Stack Overflow
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_dsa_stacks.asp
Stacks with Python
To better understand the benefits with using arrays or linked lists to implement stacks, you should check out this page that explains how arrays and linked lists are stored in memory. This is how a stack can be implemented using a linked list. ... class Node: def __init__(self, value): self.value = value self.next = None class Stack: def __init__(self): self.head = None self.size = 0 def push(self, value): new_node = Node(value) if self.head: new_node.next = self.head self.head = new_node self.size += 1 def pop(self): if self.isEmpty(): return "Stack is empty" popped_node = self.head self.head
Top answer
1 of 12
16

I corrected a few problems below. Also, a 'stack', in abstract programming terms, is usually a collection where you add and remove from the top, but the way you implemented it, you're adding to the top and removing from the bottom, which makes it a queue.

class myStack:
     def __init__(self):
         self.container = []  # You don't want to assign [] to self - when you do that, you're just assigning to a new local variable called `self`.  You want your stack to *have* a list, not *be* a list.

     def isEmpty(self):
         return self.size() == 0   # While there's nothing wrong with self.container == [], there is a builtin function for that purpose, so we may as well use it.  And while we're at it, it's often nice to use your own internal functions, so behavior is more consistent.

     def push(self, item):
         self.container.append(item)  # appending to the *container*, not the instance itself.

     def pop(self):
         return self.container.pop()  # pop from the container, this was fixed from the old version which was wrong

     def peek(self):
         if self.isEmpty():
             raise Exception("Stack empty!")
         return self.container[-1]  # View element at top of the stack

     def size(self):
         return len(self.container)  # length of the container

     def show(self):
         return self.container  # display the entire stack as list


s = myStack()
s.push('1')
s.push('2')
print(s.pop())
print(s.show())
2 of 12
5

Assigning to self won't turn your object into a list (and if it did, the object wouldn't have all your stack methods any more). Assigning to self just changes a local variable. Instead, set an attribute:

def __init__(self):
    self.stack = []

and use the attribute instead of just a bare self:

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

Also, if you want a stack, you want pop() rather than pop(0). pop(0) would turn your data structure into a(n inefficient) queue.

Discussions

Implement a stack class in Python - Code Review Stack Exchange
Problem : Implement a stack class in Python. More on codereview.stackexchange.com
๐ŸŒ codereview.stackexchange.com
January 23, 2018
how to use the Stack()?
There's no type called Stack in the Python standard library. The list type supports all the operations of a stack and thus can be used as one, which is the easiest option: stack = [] stack.append(1) # Push stack[-1] # Peek stack.pop() # Pop There's also collections.deque if performance is a concern. "Deque" stands for "double-ended queue" and is an efficient data structure that can be used as either a stack or a queue. Documentation: https://docs.python.org/3/library/collections.html#collections.deque More on reddit.com
๐ŸŒ r/learnpython
4
3
October 26, 2022
Discussing and Implementing a Stack in Python
Python doesn't seem to be the right language to do this in, just because Python lists can be treated exactly like stacks. class Stack(list): push = list.append size_of = list.__len__ def peek(self): return self[-1] def is_empty(self): return not self You're avoiding a lot of the dirty little problems that you need to deal with when implementing data structures, primarily the question of when to reallocate memory and move everything. Maybe I'm a little old fashioned about this, but I think to get a real understanding of this stuff you need to use a low-level language like C that requires you to manage your own memory. More on reddit.com
๐ŸŒ r/learnpython
4
5
February 13, 2018
I don't understand how Python 3 uses stacks in recursion.
I am trying to understand how to program a merge sort but I don't understand how Python 3 uses stacks, I think that Iโ€ฆ More on reddit.com
๐ŸŒ r/learnprogramming
28
21
February 27, 2025
๐ŸŒ
Codecademy
codecademy.com โ€บ article โ€บ create-a-stack-in-python
Stack in Python: How to Build a Python Stack Data Structure | Codecademy
Learn to implement a stack in Python with our step-by-step guide. Build a custom Python stack data structure using classes, `.push()`, `.pop()`, and `.peek()` methods.
๐ŸŒ
iO Flood
ioflood.com โ€บ blog โ€บ python-stack
Python Stack Guide: Setup, Usage, Examples
February 10, 2024 - As you become more comfortable with Python and stacks, you might find it useful to implement a stack using a class. This approach provides a cleaner, more organized way to handle stacks and can make your code more readable and maintainable.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ stack-in-python
Stack in Python - GeeksforGeeks
Below are some common ways to implement a stack: 1. Using a List: Python lists support stack operations using built-in methods like append() and pop(). ... Example: Here, elements are added to the stack using append() and removed using pop() ...
Published ย  May 19, 2026
๐ŸŒ
Built In
builtin.com โ€บ articles โ€บ stack-in-python
A Complete Guide to Stacks in Python | Built In
Python provides multiple ways to implement stacks, including lists, collections.deque and the queue module. Python lists can be used as stacks with append() and pop(), but they have performance limitations due to dynamic resizing and inefficient ...
๐ŸŒ
Real Python
realpython.com โ€บ how-to-implement-python-stack
How to Implement a Python Stack โ€“ Real Python
July 31, 2023 - The concern with using deque in ... in that class, and those are not specifically designed to be atomic, nor are they thread safe. So, while itโ€™s possible to build a thread-safe Python stack using a deque, doing so exposes yourself to someone misusing it in the future and causing race conditions. Okay, if youโ€™re threading, you canโ€™t use list for a ...
Find elsewhere
๐ŸŒ
Sanfoundry
sanfoundry.com โ€บ python-program-implement-stack
Stack Program in Python - Sanfoundry
May 30, 2022 - 6. Create an instance of Stack and present a menu to the user to perform operations on the stack. ... Here is the source code of a Python program to implement a stack. The program output is shown below. class Stack: def __init__(self): self.items ...
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ python_data_structure โ€บ python_stack.htm
Python - Stack
The remove function in the following program returns the top most element. we check the top element by calculating the size of the stack first and then use the in-built pop() method to find out the top most element. class Stack: def __init__(self): ...
๐ŸŒ
Runestone Academy
runestone.academy โ€บ ns โ€บ books โ€บ published โ€บ pythonds โ€บ BasicDS โ€บ ImplementingaStackinPython.html
4.5. Implementing a Stack in Python โ€” Problem Solving with Algorithms and Data Structures
As we described in Chapter 1, in Python, as in any object-oriented programming language, the implementation of choice for an abstract data type such as a stack is the creation of a new class. The stack operations are implemented as methods. Further, to implement a stack, which is a collection ...
๐ŸŒ
w3resource
w3resource.com โ€บ python-exercises โ€บ oop โ€บ python-oop-exercise-6.php
Python OOP: Stack class with push and pop methods
July 9, 2025 - ... # Define a class called Stack to implement a stack data structure class Stack: # Initialize the stack with an empty list to store items def __init__(self): self.items = [] # Push an item onto the stack def push(self, item): self.items.a...
๐ŸŒ
Software Testing Help
softwaretestinghelp.com โ€บ home โ€บ python โ€บ python stack โ€“ what is it and how to implement stack in python
Python Stack - What is it and How to Implement Stack in Python
April 1, 2025 - This Python queue module can be helpful when the developer is working with multiple threads and performing parallel computing. In this method, we will use โ€œ .put() โ€ and โ€œ .get() โ€œ to perform insertion and deletion of the elements from the Stack. In this example, we are inserting the elements to the stack and deleting the elements from the stack using the functions mentioned above. ``` from queue import LifoQueue # Importing the class demo_stack = LifoQueue() demo_stack.put('A') # Inserting the elements demo_stack.put('B') demo_stack.put('C') print(demo_stack) demo_stack.get() # Deleting the elements demo_stack.get() demo_stack.get() print(demo_stack) ```
๐ŸŒ
Medium
medium.com โ€บ @rajathk95 โ€บ stack-implementation-on-python-with-object-oriented-programming-caa3a3a1e8b5
Stack implementation on Python with Object Oriented Programming | by Rayat | Medium
August 25, 2024 - There are some modules built for it like queue, collections which can be tinkered for stack, none of it will be used in a enterprise level production ready code. And thatโ€™s what we will be focusing here and now. There are many ways to implement Stacks. But I am gonna show you 2 OOPs based methods. ... This is general straight forward way of implementing stack with a List and performing actions to that list such that we create a data structure that functions in LIFO. class Stack: def __init__(self): self.items = [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[-1] def __str__(self): return str(self.items) # main path if __name__ == "__main__": s = Stack() print(s) s.push(2) print(s) s.push(4) s.push(6) s.push(8) print(s) print(s.pop()) print(s) print(s.peek())
๐ŸŒ
Runestone Academy
runestone.academy โ€บ ns โ€บ books โ€บ published โ€บ pythonds3 โ€บ BasicDS โ€บ ImplementingaStackinPython.html
3.5. Implementing a Stack in Python โ€” Problem Solving with Algorithms and Data Structures 3rd edition
As we described in Chapter 1, in Python, as in any object-oriented programming language, the implementation of choice for an abstract data type such as a stack is the creation of a new class. The stack operations are implemented as methods. Further, to implement a stack, which is a collection ...
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ python-program-to-implement-a-stack
Python Program to Implement a Stack
April 15, 2021 - Here's a complete stack implementation with push, pop, and empty check operations ? class Stack: def __init__(self): self.items = [] def is_empty(self): return len(self.items) == 0 def push(self, data): self.items.append(data) print(f"Pushed {data} to stack") def pop(self): if self.is_empty(): return "Stack is empty" return self.items.pop() def peek(self): if self.is_empty(): return "Stack is empty" return self.items[-1] def display(self): if self.is_empty(): return "Stack is empty" return self.items # Create a stack instance stack = Stack() # Demonstrate stack operations stack.push(10) stack.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ implementation-of-stack-in-python-using-list
Implementation of Stack in Python using List - GeeksforGeeks
July 23, 2025 - In this example, we will implement a stack class and we will implement all the stack opertion like push, pop, top, empty, and size by the help of class method.
๐ŸŒ
Medium
machine-learning-made-simple.medium.com โ€บ implementing-stacks-from-basic-to-more-advanced-concepts-98fb06924936
Implementing Stacks- From Basic to more advanced concepts | by Devansh | Medium
November 22, 2023 - Also note that we build the stack on an array list in Python, which has dynamic resizing built in. class Stack: def __init__(self): self.items = [] def push(self, item): """Add an item to the top of the stack.""" self.items.append(item) def ...
๐ŸŒ
Medium
medium.com โ€บ @mitchhuang777 โ€บ implementing-a-stack-data-structure-in-python-aeb68279bf96
Implementing a Stack Data Structure in Python | by Mitch Huang | Medium
May 17, 2023 - In Python, we can implement a stack using a list or a custom class. Here is an example using a list: stack = Stack() # push elements to the stack stack.push(1) stack.push(2) stack.push(3) # pop elements from the stack print(stack.pop()) # output: ...
๐ŸŒ
Great Learning
mygreatlearning.com โ€บ blog โ€บ it/software development โ€บ stack in python: how to implement python stack?
Stack in Python: How To Implement Python Stack?
October 24, 2024 - We use the class and object approach of Python OOP to create linked lists in Python. We have certain functions at our disposal in Python that are useful in stack implementation, such as getSize(), isEmpty(), push(n), and pop().