What is Deque?
Deque (Doubly Ended Queue) in Python allows elements to be added and removed from either end. The Deque module is a part of the collections library. A deque is preferable over a list whenever we need to perform append and pop operations quickly from both ends of a container, as deque implements append and pop operations with an O(1) time complexity as compared to a list, which has an O(n) time complexity.
How to use Deque in Python?
To use a deque in your Python code, you need to import the "collections" library first:
Methods for modifying a deque
The following is a brief description of the methods used to modify the deque:
The append() is used to append the data item in its parameter to the right end of the deque.
The appendleft() is used to add the data item in its parameter to the left end of the deque.
Method insert(index, value)
The insert() is used to insert the value described in the "x" parameter into the index number "i" specified in the parameters.
The extend() is used to insert multiple data items into the right end of a deque. The passed parameter is repeated.
The extendleft() is used to insert multiple items of data into the left end of a deque. The passed parameter is repeated. The order is also reversed as a result of left additions.
The pop() is used to remove a data item from the right end of the deque.
The popleft() method removes an item from the right end of a deque.
The remove() method removes the first occurrence of the value specified in the parameters.
The count() method counts the total number of occurrences of the value specified in the parameters.
Method index(element, begin, end)
The index() returns the first index value specified in the parameters and starts the search from the beginning to the end of the index.
The rotate() is used to rotate the deque by the number specified in the parameters. If the set number is negative, the rotation is to the left. The rest of the rotation is to the right.
The reverse() is used to reverse the order of the deque data items.