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:
Method append()
The append() is used to append the data item in its parameter to the right end of the deque.
Method appendleft()
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.
Method extend(iterable)
The extend() is used to insert multiple data items into the right end of a deque. The passed parameter is repeated.
Method extendleft(iterable)
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.
Method pop()
The pop() is used to remove a data item from the right end of the deque.
Method popleft()
The popleft() method removes an item from the right end of a deque.
Method remove()
The remove() method removes the first occurrence of the value specified in the parameters.
Method count()
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.
Method rotate()
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.
Method reverse()
The reverse() is used to reverse the order of the deque data items.