Double-Ended Queues in Python
The regular queue data structure follows FIFO(First in First Out) rule. Queue is a great data structure, but when it comes to adding elements at the end or removing elements from the beginning, it gets complicated.
This is where Double-Ended aka deque comes into the picture. Deque supports adding and removing elements from both ends.
Generally, deques are implemented using a doubly LinkedList. However, Python collections
the built-in module has a deque
class, which makes it easy to use.
Let's look at the few important functions of deque
- Import the
deque
class
from collections import deque
Create a
deque
with numbersfrom collections import deque # deque with elements prime_numbers = deque([3,5,7,11]) print(prime_numbers)
Append the element at the right end
prime_numbers.append(13)
print(prime_numbers) #[3, 5, 7, 11, 13]
- Append element at the left end
prime_numbers.appendleft(2)
print(prime_numbers)# [2, 3, 5, 7, 11, 13]
- Pop element from the right end
prime_numbers.pop() #13
Pop element from the left end
prime_numbers.popleft() # 2
Let's see all these methods in animation.
I hope you like this content, if so please like and share it with your friends. Follow me for more such content. #WeMakeDevs