Double-Ended Queues in Python

·

1 min read

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

  1. Import the deque class

from collections import deque

  1. Create a deque with numbers

    from collections import deque
    
    # deque with elements
    prime_numbers = deque([3,5,7,11])
    print(prime_numbers)
    
  2. Append the element at the right end

prime_numbers.append(13)
print(prime_numbers) #[3, 5, 7, 11, 13]
  1. Append element at the left end
prime_numbers.appendleft(2)
print(prime_numbers)# [2, 3, 5, 7, 11, 13]
  1. Pop element from the right end
prime_numbers.pop() #13
  1. 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