
226 views
Python Stack & Queue
The Python, you can implement a stack and a queue using various data structures and libraries. Here’s how to implement both a stack and a queue:
Stack:
A stack is a linear data structure that follows the Last-In, First-Out (LIFO) principle, meaning that the last element added is the first one to be removed.
- Using Lists: You can implement a stack using Python lists by using the
append()
method to push elements onto the stack and thepop()
method to remove elements from the top of the stack:
stack = []
# Push elements onto the stack
stack.append(1)
stack.append(2)
stack.append(3)
# Pop elements from the stack
popped_element = stack.pop()
print("Popped Element:", popped_element)
- Using
collections.deque
: Thecollections
module provides adeque
(double-ended queue) data structure, which can be used to implement a stack with efficient push and pop operations:
from collections import deque
stack = deque()
# Push elements onto the stack
stack.append(1)
stack.append(2)
stack.append(3)
# Pop elements from the stack
popped_element = stack.pop()
print("Popped Element:", popped_element)
Queue:
A queue is a linear data structure that follows the First-In, First-Out (FIFO) principle, meaning that the first element added is the first one to be removed.
- Using Lists: You can implement a simple queue using Python lists by using the
append()
method to enqueue elements and thepop(0)
method to dequeue elements:
queue = []
# Enqueue elements
queue.append(1)
queue.append(2)
queue.append(3)
# Dequeue elements
dequeued_element = queue.pop(0)
print("Dequeued Element:", dequeued_element)
- Using
collections.deque
: Thecollections
module also provides adeque
that can be used to implement a queue. It offers efficient enqueue and dequeue operations:
from collections import deque
queue = deque()
# Enqueue elements
queue.append(1)
queue.append(2)
queue.append(3)
# Dequeue elements
dequeued_element = queue.popleft()
print("Dequeued Element:", dequeued_element)
- Using
queue.Queue
: Thequeue
module provides theQueue
class, which is a thread-safe queue implementation. It can be used for implementing a simple queue:
import queue
q = queue.Queue()
# Enqueue elements
q.put(1)
q.put(2)
q.put(3)
# Dequeue elements
dequeued_element = q.get()
print("Dequeued Element:", dequeued_element)
Choose the implementation that best suits your needs based on your specific use case and requirements. If you need thread-safe queues, consider using the queue.Queue
class. For basic stack and queue operations, using lists or collections.deque
should suffice.