Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

Using list as stack in Python

📅 2012-Apr-18 ⬩ ✍️ Ashwin Nanjappa ⬩ 📚 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