Deque (Doubly Ended Queue) is a type of collection in Python.
This is used when we need to perform quicker append and pop operations from the start and end of the container. And that is preferred to use at that time than using lists.
This is because deques provide O(1) time complexity while lists give O(n).
from collections import deque
# Declaring deque
queue = deque( ['value1', 'value2', 'value3'] )
Various functions are used to access items in a deque. Let's go through some of them using the above example.
append()
queue = append('value5')
#deque(['value1','value2','value3','value5'])
appendleft()
queue = appendleft('value6') #deque(['value6','value1','value2','value3','value5'])
pop()
queue = pop()
#deque(['value1','value2','value3'])
popleft()
queue = popleft()
#deque(['value1','value2','value3','value5'])
index(element, beginning, end) - It returns the first index of the value stated in arguments, searching from beginning to end.
print(de.index('value2',0,2))
# 1
insert(i, a) - this will insert a value that is mentioned in the argument at index (i).
print(de.insert(2,'value8'))
# deque(['value1','value2','value8','value3','value5'])
remove(val) - this will remove the first occurrence of the value mentioned in the argument (val)
print(de.remove('value3'))
# deque(['value1','value2','value8','value5'])
count(val) - this will return the number of elements that has been mentioned in the arguments (val).
print(de.count('value8'))
# 1
Comments