What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

Python Deque: Example, Implementation & Methods (with code)

  • Mar 15, 2023
  • 8 Minutes Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Abrar Ahmed
Python Deque: Example, Implementation & Methods (with code)

With the Queue, users can create a FIFO (First In, First Out) orderly list. The LIFO (Last in, First Out) queue, which is used by Python's Deque, is the reverse of FIFO. In this guide, we will learn all about Deque in Python with examples and code.

What is deque() in Python?

A class called deque can be found in Python's collections module which is optimized for quick operations like appending and popping items from either end of the underlying data structure. Deque is short for "double-ended queue", which can also be used as a basic queue or stack data structure.

Deque offers O(1) time complexity for append and pop operations from both ends of the container, it is favored over a list when we need faster append and pop operations from both ends of the container. In addition, these operations are thread-safe and memory-efficient. Due to these traits, Python deques are ideal for constructing specialized queues and stacks.

You can restrict the utmost duration of your deques, making them suitable for use as a gathering of recently viewed items. When a deque's limit is reached, it discards items from one end whenever new items are introduced to the other end.

You can understand deque easily with the below illustration:

how python deque works

How to import deque in python?

You must import the collections module before you can use a deque in your Python code. This provides a collection of specialized container data types to provide additional functionality compared to the built-in types.

from collections import deque

 

How to implement python deque?

A deque is defined in the code below by giving the list's name (list_name) to the deque() module, which was loaded from the collections library. Furthermore, we can see that no special class is required to make use of these in-built methods. They don't need any extra steps to be put into effect. Let's look at an example:

from collections import deque

list_name=deque(['book','pen','scale','eraser','sharpener'])

print(list_name)

 

Output:

deque(['book', 'pen', 'scale', 'eraser', 'sharpener'])

 

The declared Deque for the users has then been printed. The declared Deque holding the list titles is thus effectively printed.

Is deque better than a list in Python?

The deque and list are both container types with different characteristics.  But Deque is more optimized than a list for adding and removing of elements from both ends and provides a consistent O(1) time complexity. The deques allow for thread-safe, memory-efficient operations.

The time complexity of Python's list methods pop from the end and append is also O(1). But If you need to implement a queue or a stack where items are appended and popped from both ends frequently, a deque may be a better choice. 

Size of a deque

In order to find the size of a deque len(dequeue) command is used. This len(queue) returns the current size/ length of the dequeue. In the below example, first, the deque is initialized and the current size of the deque is displayed.

Then using the pop() operation element from the right end is deleted. Further, the modified deque is printed along with its size.

from collections import deque

d = deque([5,7,9,11,13])

print("current Deque: ", d)

print(f"The size of deque: {len(d)}")

d.pop()

print("\nUpdated deque is: ", end = '')

print(d)

print(f"The size of deque: {len(d)}")

 

Output:

current Deque: deque([5, 7, 9, 11, 13])

The size of deque: 5 

Updated deque is: deque([5, 7, 9, 11])

The size of deque: 4

 

What are the different deque methods?

Two categories of restricted deque inputs exist: The output of an Output Restricted Deque is bounded at one end, while input is allowed at both. One end of an input-restricted deque can only add items, but both can delete items.

Deque supports a number of different operations. There are two methods for appending: append() and appendleft(). Data elements can be appended to the right end of a deque using the append() method. The appendleft() method is used to append the piece of data passed to it to the left end of the deque.

Both pop() and popleft() can be used for efficiently popping components from a deque. Data can be removed from the right end of the deque using the pop() method. The data item at the left end of the deque is removed using the popleft() method.

Let us look at the code:

from collections import deque

new =deque([3,4,5,6])

print("deque: ", new)

new.append(7)

print("\nThe updated deque is : ")

print(new)

new.appendleft(8)

print("\nThe updated deque is : ")

print(new)

new.pop()

print("\nThe updated deque is : ")

print(new)

new.popleft()

print("\nThe updated deque is : ")

print(new)

 

Output:

deque: deque([3, 4, 5, 6]) 

The updated deque is :

deque([3, 4, 5, 6, 7]) 

The updated deque is :

deque([8, 3, 4, 5, 6, 7])

The updated deque is :

deque([8, 3, 4, 5, 6]) 

The updated deque is :

deque([3, 4, 5, 6])

 

All items in a deque can be accessed using the following four methods: index(element, begin, end), insert(i, x), remove(), and count (). The index() method returns the initial index value from the parameters, allowing you to probe between the given ranges of values (beginning with index) and ending with the end index.

Inserting the value outlined by parameter 'x' at position number ‘i’ specified in parameters is done using the insert() method. The first instance of the number provided in the parameters is removed using the remove () method. The count() method is used to count the overall number of instances of the value provided in the parameters.

Check out the code:

from collections import deque

new =deque([3,4,5,6])

print ("5 occurs for first time at a position : ")

print (new.index(5,1,3))

new.insert(4,5)

print ("Insert 5 at fifth position in deque: ")

print (new)

print ("Count of 5 is : ")

print (new.count(5))

new.remove(5)

print ("After removing first repeated 5 in the deque: ")

print (new)

 

Output:

5 occurs for first time at a position : 
2
Insert 5 at fifth position in deque: 
deque([3, 4, 5, 6, 5])
Count of 5 is : 
2
After removing first repeated 5 in the deque:
deque([3, 4, 6, 5])

Deque supports a wide variety of operations, such as extend(iterable), extendleft(iterable), reverse(), and rotate(). Multiple data elements can be inserted at the right end of the deque using the extend() method.

Iterable is the nature of the parameter that was given. Inserting numerous data elements at the left end of the deque is done using the extendleft() method. Iterable is the type of parameter that was provided. As an additional, left appends result in an inverted Sequence.

Data elements in a deque can be flipped around with the help of the reverse() method. Rotate the deque by the number specified in the parameters using the rotate() method. It rotates to the left if the specified value is less than zero. Anything else will rotate to the right.

Here is the code:

from collections import deque

new =deque([3,4,5,6])

new.extend([7,8,9])

print ("Extended deque at end is : ")

print (new)

new.extendleft([10,11,12])

print ("Deque after extending deque: ")

print (new)

new.reverse()

print ("Reversed deque is : ")

print (new)

new.rotate(-3)

print ("Rotated deque is : ")

print (new)

 

Output:

Extended deque at end is :

deque([3, 4, 5, 6, 7, 8, 9])

Deque after extending deque:

deque([12, 11, 10, 3, 4, 5, 6, 7, 8, 9])

Reversed deque is :

deque([9, 8, 7, 6, 5, 4, 3, 10, 11, 12])

Rotated deque is :

deque([6, 5, 4, 3, 10, 11, 12, 9, 8, 7])

 

Conclusion

At this point, you should have a complete grasp of the deque in python with different methods. Python's deque is a low-level and highly streamlined double-ended queue that can be used to build them in a sleek, efficient, and Pythonic way. Happy Learning :)

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Abrar Ahmed
An ambivert individual with a thirst for knowledge and passion to achieve. Striving to connect Artificial Intelligence in all aspects of life. I am also an avid coder and partake in coding challenges all the time on Leetcode and CodeChef.