Algorithmsefficient stack usage

Efficient Stack Usage in Python

TT
Testlaa Team
May 14, 20261 min read

Use the end of a list as the top: append and pop() are amortized O(1). Avoid pop(0) for a stack mental model.

Try this in Python

st: list[int] = []
for x in range(5):
    st.append(x)
while st:
    print(st.pop(), end=" ")
print()

Key takeaways

  • End-of-list operations keep cache-friendly sequential memory.
  • Reserve collections.deque when you truly need both ends fast.
  • Measure before micro-optimizing.

Tags:

Stacks & queuesPythonStudents