A deque stands for Double-Ended Queue. It is a data structure that allows adding and removing elements from both ends efficiently. Unlike regular queues, which are typically operated on using FIFO (First In, First Out) principles, a deque supports both FIFO and LIFO (Last In, First Out) operations.
Example:
Python
from collections import deque
# Declaring deque
de = deque(['name','age','DOB'])
print(de)
Outputdeque(['name', 'age', 'DOB'])
Deque in PythonTypes of Restricted Deque Input
- Input Restricted Deque: Input is limited at one end while deletion is permitted at both ends.
- Output Restricted Deque: output is limited at one end but insertion is permitted at both ends.
Operations on deque
Here’s a table listing built-in operations of a deque in Python with descriptions and their corresponding time complexities:
Operation | Description | Time Complexity |
---|
append(x) | Adds x to the right end of the deque. | O(1) |
---|
appendleft(x) | Adds x to the left end of the deque. | O(1) |
---|
pop() | Removes and returns an element from the right end of the deque. | O(1) |
---|
popleft() | Removes and returns an element from the left end of the deque. | O(1) |
---|
extend(iterable) | Adds all elements from iterable to the right end of the deque. | O(k) |
---|
extendleft(iterable) | Adds all elements from iterable to the left end of the deque (reversed order). | O(k) |
---|
remove(value) | Removes the first occurrence of value from the deque. Raises ValueError if not found. | O(n) |
---|
rotate(n) | Rotates the deque n steps to the right. If n is negative, rotates to the left. | O(k) |
---|
clear() | Removes all elements from the deque. | O(n) |
---|
count(value) | Counts the number of occurrences of value in the deque. | O(n) |
---|
index(value) | Returns the index of the first occurrence of value in the deque. Raises ValueError if not found. | O(n) |
---|
reverse() | Reverses the elements of the deque in place. | O(n) |
---|
Appending and Deleting Dequeue Items
- append(x): Adds x to the right end of the deque.
- appendleft(x): Adds x to the left end of the deque.
- extend(iterable): Adds all elements from the iterable to the right end.
- extendleft(iterable): Adds all elements from the iterable to the left end (in reverse order).
- remove(value): Removes the first occurrence of the specified value from the deque. If value is not found, it raises a ValueError.
- pop(): Removes and returns an element from the right end.
- popleft(): Removes and returns an element from the left end.
- clear(): Removes all elements from the deque.
Python
from collections import deque
dq = deque([10, 20, 30])
# Add elements to the right
dq.append(40)
# Add elements to the left
dq.appendleft(5)
# extend(iterable)
dq.extend([50, 60, 70])
print("After extend([50, 60, 70]):", dq)
# extendleft(iterable)
dq.extendleft([0, 5])
print("After extendleft([0, 5]):", dq)
# remove method
dq.remove(20)
print("After remove(20):", dq)
# Remove elements from the right
dq.pop()
# Remove elements from the left
dq.popleft()
print("After pop and popleft:", dq)
# clear() - Removes all elements from the deque
dq.clear() # deque: []
print("After clear():", dq)
Output:
After extend([50, 60, 70]): deque([5, 10, 20, 30, 40, 50, 60, 70])
After extendleft([0, 5]): deque([5, 0, 5, 10, 20, 30, 40, 50, 60, 70])
After remove(20): deque([5, 0, 5, 10, 30, 40, 50, 60, 70])
After pop and popleft: deque([0, 5, 10, 30, 40, 50, 60])
After clear(): deque([])
Accessing Item and length of deque
- Indexing: Access elements by position using positive or negative indices.
- len(): Returns the number of elements in the deque.
Python
import collections
dq = collections.deque([1, 2, 3, 3, 4, 2, 4])
# Accessing elements by index
print(dq[0])
print(dq[-1])
# Finding the length of the deque
print(len(dq))
Count, Rotation and Reversal of a deque
- count(value): This method counts the number of occurrences of a specific element in the deque.
- rotate(n): This method rotates the deque by n steps. Positive n rotates to the right and negative n rotates to the left.
- reverse(): This method reverses the order of elements in the deque.
Python
from collections import deque
# Create a deque
dq = deque([10, 20, 30, 40, 50, 20, 30, 20])
# 1. Counting occurrences of a value
print(dq.count(20)) # Occurrences of 20
print(dq.count(30)) # Occurrences of 30
# 2. Rotating the deque
dq.rotate(2) # Rotate the deque 2 steps to the right
print(dq)
dq.rotate(-3) # Rotate the deque 3 steps to the left
print(dq)
# 3. Reversing the deque
dq.reverse() # Reverse the deque
print(dq)
Output3
2
deque([30, 20, 10, 20, 30, 40, 50, 20])
deque([20, 30, 40, 50, 20, 30, 20, 10])
deque([10, 20, 30, 20, 50, 40, 30, 20])
Similar Reads
Python Collections Module The collection Module in Python provides different types of containers. A Container is an object that is used to store different objects and provide a way to access the contained objects and iterate over them. Some of the built-in containers are Tuple, List, Dictionary, etc. In this article, we will
13 min read
Namedtuple in Python Python supports a type of container dictionary called "namedtuple()" present in the module "collections". In this article, we are going to see how to Create a NameTuple and operations on NamedTuple.What is NamedTuple in Python?In Python, NamedTuple is present inside the collections module. It provid
8 min read
Deque in Python A deque stands for Double-Ended Queue. It is a data structure that allows adding and removing elements from both ends efficiently. Unlike regular queues, which are typically operated on using FIFO (First In, First Out) principles, a deque supports both FIFO and LIFO (Last In, First Out) operations.E
6 min read
ChainMap in Python Python contains a container called "ChainMap" which encapsulates many dictionaries into one unit. ChainMap is member of module "collections". Example: Python3 # Python program to demonstrate # ChainMap from collections import ChainMap d1 = {'a': 1, 'b': 2} d2 = {'c': 3, 'd': 4} d3 = {'e': 5, 'f': 6}
3 min read
Python | Counter Objects | elements() Counter class is a special type of object data-set provided with the collections module in Python3. Collections module provides the user with specialized container datatypes, thus, providing an alternative to Python's general-purpose built-ins like dictionaries, lists, and tuples. Counter is a sub-c
6 min read
OrderedDict in Python OrderedDict is a subclass of Python's built-in dictionary dict that remembers the order in which keys are inserted. Unlike older versions of Python where dictionaries did not guarantee order, OrderedDict preserves insertion order reliably.Note: From Python 3.7 onwards, the built-in dict also preserv
7 min read
Defaultdict in Python In Python, defaultdict is a subclass of the built-in dict class from the collections module. It is used to provide a default value for a nonexistent key in the dictionary, eliminating the need for checking if the key exists before using it.Key Features of defaultdict:When we access a key that doesn'
6 min read
Collections.UserDict in Python An unordered collection of data values that are used to store data values like a map is known as Dictionary in Python. Unlike other Data Types that hold only a single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized. Note: For mo
2 min read
Collections.UserList in Python Python Lists are array-like data structure but unlike it can be homogeneous. A single list may contain DataTypes like Integers, Strings, as well as Objects. List in Python are ordered and have a definite count. The elements in a list are indexed according to a definite sequence and the indexing of a
2 min read
Collections.UserString in Python Strings are the arrays of bytes representing Unicode characters. However, Python does not support the character data type. A character is a string of length one. Example: Python3 # Python program to demonstrate # string # Creating a String # with single Quotes String1 = 'Welcome to the Geeks World'
2 min read