How to implement a stack in Python

3 Answers

0 votes
stack = []

# Push elements
stack.append(1)
stack.append(2)
stack.append(3)
stack.append(4)

# Pop elements
print(stack.pop())  # 4
print(stack.pop())  # 3

print()

# Peek at the top
print(stack[0])  # 1

print()

# Check if empty
print(len(stack) == 0)



'''
run:

4
3

1

False

'''

 



answered Aug 14, 2025 by avibootz
0 votes
from collections import deque

stack = deque()

# Push
stack.append('a')
stack.append('b')
stack.append('c')
stack.append('d')

# Pop
print(stack.pop())  # d

print()
print(stack)
print()

# Peek
print(stack[0]) # a




'''
run:

d

deque(['a', 'b', 'c'])

a

 



answered Aug 14, 2025 by avibootz
0 votes
from queue import LifoQueue

stack = LifoQueue()

# Push
stack.put(10)
stack.put(20)
stack.put(30)
stack.put(40)

# Pop
print(stack.get())  # 40

print()

# Check if empty
print(stack.empty())  # False



'''
run:

40

False

'''

 



answered Aug 14, 2025 by avibootz

Related questions

1 answer 70 views
1 answer 75 views
1 answer 86 views
2 answers 89 views
1 answer 92 views
...