In Python, a stack and a queue are both abstract data types that can be implemented using built-in data structures such as lists or dequeues from the collections
module.
A stack is a data structure that follows the Last-In-First-Out (LIFO) principle. The last element added to the stack will be the first one to be removed. The two most important operations on a stack are push
, which adds an element to the top of the stack, and pop
, which removes the top element from the stack. Here’s an example implementation of a stack in Python using a list:
stack = [] # Push elements onto the stack stack.append(1) stack.append(2) stack.append(3) # Pop elements off the stack print(stack.pop()) # prints 3 print(stack.pop()) # prints 2 print(stack.pop()) # prints 1
A queue, on the other hand, follows the First-In-First-Out (FIFO) principle. The first element added to the queue will be the first one to be removed. The two most important operations on a queue are enqueue
, which adds an element to the end of the queue, and dequeue
, which removes the first element from the queue. Here’s an example implementation of a queue in Python using a list:
from collections import deque queue = deque() # Enqueue elements onto the queue queue.append(1) queue.append(2) queue.append(3) # Dequeue elements off the queue print(queue.popleft()) # prints 1 print(queue.popleft()) # prints 2 print(queue.popleft()) # prints 3
Note that while both of these implementations use lists, there are other built-in data structures in Python that can be used to implement stacks and queues more efficiently, such as deque
from the collections
module, or even queue.LifoQueue
and queue.Queue
classes from the queue
module.