Sobes.tech
Junior — Middle

What data structures can be used to build a stack in Python?

sobes.tech AI

Answer from AI

In Python, a stack can be implemented using several data structures:

  1. List — the simplest way. The methods append() and pop() allow adding and removing elements from the end of the list, which corresponds to stack behavior.
stack = []
stack.append(1)  # push element
stack.append(2)
print(stack.pop())  # pop element, outputs 2
  1. collections.deque — a double-ended queue that is more efficient than a list for adding and removing elements from both ends.
from collections import deque
stack = deque()
stack.append(1)
stack.append(2)
print(stack.pop())  # 2
  1. queue module — the LifoQueue class implements a thread-safe stack, useful in multi-threaded applications.
from queue import LifoQueue
stack = LifoQueue()
stack.put(1)
stack.put(2)
print(stack.get())  # 2

Thus, for simple cases, a list is sufficient; for more efficient or thread-safe implementations, deque or LifoQueue are recommended.