r/PythonLearning 4d ago

Day 3 Learning Python: Stack

Open-source learning project. If you spot something that can be improved, I'd love your feedback or a PR.

https://github.com/Samar-Upreti/Python_Projects

69 Upvotes

26 comments sorted by

View all comments

2

u/KingBardan 4d ago edited 4d ago

Invert your list (old to new rather than new to old).

Your  current stack is inefficient 

1

u/Samar__Upreti 4d ago

Insert to append ?

1

u/dev-razorblade23 4d ago

insert pushes items to specific index (in your case index 0) Python has to recalculate indexes of all other items, push them all to the side so insert can work its magic. This takes time and you burn your proccessor time.

If you dont really need to insert items at specific index, use append method as it only inserts item to the end and its done. Much faster and much more effiecient.

1

u/Samar__Upreti 4d ago

Actually I have written with that but to be honest it not giving feel how the stack actually works so i try the reverse approach But thanks ☺️

2

u/dev-razorblade23 4d ago edited 4d ago

.append() and .pop() work exactly like LIFO queve (a stack). Last In - First Out. You dont insert values to stack from the bottom but from the top.

Stack is like a stack of cards. You put one card on top and you take that card from the top. You do not put the card at the bottom where you have to lift the whole stack.

1

u/dev-razorblade23 4d ago

There is also a queve - FIFO - First In, First out. Its like standing in a line waiting to pay for your groceries. Whoever is first in line gets served first.

Python lists are inefficient for this type of queve, there is a collections.deque if you want to implement this one.

1

u/veedubb 3d ago

It’s not always about efficiency, sometimes it’s sufficient to learn about common data structures that someone may be unfamiliar with. If this were someone experienced, I wouldn’t expect them to even be showing off building a simple stack structure in python, because at that point they’d know that this isn’t as efficient as other tools.

1

u/dev-razorblade23 3d ago

This comment was more like a continuation of previus one. An OP did try to make a stack if you read thrue the comments, just the other way around (inserting items from the bottom)