Essentially, python does not have stack and queues like programming languages like Java. In this post, we will be exploring the implementation of Python stack and queues using the collections library.
Python stack and queues
Stacks and queues are one of the earliest data structures in computer science and here are their implementations in Python programming.
Stacks
Stacks are data structures where data items are inserted and as well deleted or removed from the end. They are referred to as last in first out or LIFO.
Think of stacks as stacks of books. You can easily place other books on top of the stack and to get a book inside the stack, you have to remove the ones on top until you get to the book that you want to remove.
Demonstrating the stack data structure with a Python list, the two major operations that can be performed are pop() and append().
pop() method
The pop method removes the last data item in a list and returns the item. For example:
L = [1,2,3,4,5] last = L.pop() print(last) print(L) last = L.pop() print(last) print(L) #outputs #5 #[1, 2, 3, 4] #4 #[1, 2, 3]
append() method
The append method inserts data items at the end of the list as shown below:
L = [] L.append(1) print(L) L.append(2) print(L) L.append(3) print(L) #outputs #[1] #[1, 2] #[1, 2, 3]
Queues
Queues represent waiting in lines. They are otherwise known as LIFO which stands for First In First Out. Insertions are made at the end of the queue and deletions are made at the beginning.
Naturally, queues cannot be implemented in the Python list. However, by importing the deque from the collections library, queues can be implemented as shown below.
You can now use the popleft() function to remove the first items in the queue and pop() function to remove the last item in the queue.
from collections import deque L = ['mango', 'banana', 'grape', 'strawberry', 'papaya'] Q = deque(L) print(Q) first = Q.popleft() print(first) print(Q) last = Q.pop() print(last) print(Q) #outputs #deque(['mango', 'banana', 'grape', 'strawberry', 'papaya']) #mango #deque(['banana', 'grape', 'strawberry', 'papaya']) #papaya #deque(['banana', 'grape', 'strawberry'])