Junior — Middle
Can you give an example of a data structure representing a stack?
sobes.tech AI
Answer from AI
A stack is a data structure with the Last In, First Out (LIFO) principle, where the last added element is retrieved first.
In Python, a stack can be implemented using a list, with the append() method for adding elements and pop() for removing them:
stack = [] # empty stack
# Adding elements
stack.append(1)
stack.append(2)
stack.append(3)
print(stack) # [1, 2, 3]
# Removing elements
top = stack.pop()
print(top) # 3
print(stack) # [1, 2]
You can also use collections.deque for more efficient addition and removal operations from both ends, but a list is perfectly suitable for a stack.