In this Python article we want to talk about How to Implement Stacks and Queues with Python Lists, Stacks and Queues are two fundamental data structures used in computer programming to manage collections of elements. stacks and queues can be implemented using Python lists which are dynamic arrays that can grow and shrink as needed. in this article we want to talk how to implement stacks and queues using Python lists.
First of all let’s talk about stack, stack is linear data structure that follows the Last In First Out (LIFO) principle. this means that the element that is inserted last will be the first one to be removed. following code shows how to implement a stack using Python lists:
1 2 3 4 5 6 7 8 9 10 11 12 |
# Initializing an empty list stack = [] # Push operation stack.append(1) stack.append(2) stack.append(3) # Pop operation print(stack.pop()) # Output: 3 print(stack.pop()) # Output: 2 print(stack.pop()) # Output: 1 |
In the above code we have initialized an empty list called stack. after that we have used append() method to add elements to the stack which corresponds to the push operation. and finally we have used pop() method to remove elements from the stack, which corresponds to the pop operation.
Now let’s implement Queues with Python Lists, queue is linear data structure that follows the First In First Out (FIFO) principle. it means that the element is inserted first will be the first one to be removed. following code shows how to implement queue using Python lists:
1 2 3 4 5 6 7 8 9 10 11 12 |
# Initializing an empty list queue = [] # Enqueue operation queue.append(1) queue.append(2) queue.append(3) # Dequeue operation print(queue.pop(0)) # Output: 1 print(queue.pop(0)) # Output: 2 print(queue.pop(0)) # Output: 3 |
In the above code we have initialized an empty list called queue. after that we have used append() method to add elements to the queue, which corresponds to the enqueue operation. and lastly we have used pop(0) method to remove elements from the queue, which corresponds to the dequeue operation. Note that we use the index 0 to specify the position of the first element in the list.
Learn More on Python
- How to Integrate PyQt6 with OpenCV
- How to Create Button in Python & PySide6
- How to Use Qt Designer with PySide6
- How to Add Icon to PySide6 Window
- How to Load UI in Python PySide6
- How to Create RadioButton in PySide6
- How to Create ComboBox in PySide6
- How to Create CheckBox in Python PySide6
- Responsive Applications with PyQt6 Multithreading
- Event Handling in Python and PyQt6
- How to Use Stylesheets in Python PyQt6