Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,988 questions

51,933 answers

573 users

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 56 views
1 answer 64 views
1 answer 68 views
2 answers 69 views
1 answer 76 views
...