Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

Using list as stack in Python

📅 2012-Apr-18 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ list, python, stack ⬩ 📚 Archive

The humble list can be used as a stack in Python. Unlike using list as queue, using list as stack is optimal.

stk = []

for i in range( 0, 5 ):
    stk.append( i ) # Push to stack

while stk: # Stack not empty
    j = stk.pop() # Pop from stack
    print( j )

# Output: 4 3 2 1 0

© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 @codeyarns@hachyderm.io📧