logo
Python Data Structures - Interview Questions and Answers
How are stacks and queues implemented in Python? Provide code examples for each.
In Python, I can implement a stack using a list, as it supports Last In, First Out (LIFO) operations. The list’s append() and pop() methods make it easy to add and remove elements from the end, respectively. Here’s an example :
stack = []
stack.append(1) # Push element
stack.append(2)
stack.pop() # Pop element?

In this code, the stack starts empty, append adds elements to the top, and pop removes the last element. This behavior is perfect for applications like undo operations.

A queue, on the other hand, follows a First In, First Out (FIFO) structure. I can use the deque class from the collections module for efficient queue implementation. Here’s how:
from collections import deque
queue = deque()
queue.append(1) # Enqueue element
queue.append(2)
queue.popleft() # Dequeue element?

Using deque , I can add elements with append() and remove them in a FIFO manner with popleft() . This implementation is suitable for scenarios like task scheduling or buffering, where the first data added needs to be the first retrieved.