DEV Community

Discussion on: Making a Stack Data Type in Python

Collapse
 
cicirello profile image
Vincent A. Cicirello • Edited

This is all technically correct but unnecessary in Python. For a stack in Python just use a list like this:

# Initialize empty stack as empty list

stack = [ ]

# For push just use append

stack.append("world")
stack.append("hello")

# For pop just use pop

x = stack.pop() if len(stack) > 0 else None

# For top just use an index of -1

top = stack[-1] if len(stack) > 0 else None
Enter fullscreen mode Exit fullscreen mode

For a queue, import the deque type (double ended queue) from the collections module and use that.

Collapse
 
iamdurga profile image
Durga Pokharel

Yeah you are right. Thank you for pointing out. My goal was to code the theory behind the Stack but not the fast and short codes. πŸ™‚

Collapse
 
luzonaldo profile image
LuZzoO

But, the whole point is to understand what happens.

Collapse
 
furtleo profile image
Leonardo Furtado

So it's unnecessary study and implement data structures in python cuz they are implemented already???? rofl

Collapse
 
cicirello profile image
Vincent A. Cicirello

That is not at all what I said. I said nothing about data structures more generally. However, you wouldn't implement a stack in python the way described in this post. Instead, if you were implementing a stack in python to learn about stacks, you would have a much simpler stack class wrapping a python list with methods for the stack operations implemented the way I described. It still gets across main point of using right end as top of stack.

Using a python list as if it was instead a simple array, as described in this post, just encourages bad python style.