Read the first element and put it at the left end
1
Read the second element and put it at the left end
2 - > 1
Read the third element and put it at the left end
3 - > 2 - > 1
See, the order of the elements is reversed. Actually, this seems logical to me. When we do list.extend
, like this
[].extend([1, 2, 3, 4])
Last Updated : 09 May, 2022
Output:
deque(['name', 'age', 'DOB'])
Output:
The number 4 first occurs at a position:
4
The deque after inserting 3 at 5 th position is:
deque([1, 2, 3, 3, 3, 4, 2, 4])
The count of 3 in deque is:
3
The deque after deleting first occurrence of 3 is:
deque([1, 2, 3, 3, 4, 2, 4])
Output :
The deque after extending deque at end is:
deque([1, 2, 3, 4, 5, 6])
The deque after extending deque at beginning is:
deque([9, 8, 7, 1, 2, 3, 4, 5, 6])
The deque after rotating deque is:
deque([1, 2, 3, 4, 5, 6, 9, 8, 7])
The deque after reversing deque is:
deque([7, 8, 9, 6, 5, 4, 3, 2, 1])
Notice that extendleft() iterates over its input and performs the equivalent of an appendleft() for each item. The end result is the deque contains the input sequence in reverse order.,A double-ended queue, or deque, supports adding and removing elements from either end. The more commonly used stacks and queues are degenerate forms of deques, where the inputs and outputs are restricted to a single end.,Since deques are a type of sequence container, they support some of the same operations that lists support, such as examining the contents with __getitem__(), determining length, and removing elements from the middle by matching identity.,Similarly, the elements of the deque can be consumed from both or either end, depending on the algorithm being applied.
import collections
d = collections.deque('abcdefg')
print 'Deque:', d
print 'Length:', len(d)
print 'Left end:', d[0]
print 'Right end:', d[-1]
d.remove('c')
print 'remove(c):', d
$ python collections_deque.py
Deque: deque(['a', 'b', 'c', 'd', 'e', 'f', 'g'])
Length: 7
Left end: a
Right end: g
remove(c): deque(['a', 'b', 'd', 'e', 'f', 'g'])
import collections # Add to the right d = collections.deque() d.extend('abcdefg') print 'extend :', d d.append('h') print 'append :', d # Add to the left d = collections.deque() d.extendleft('abcdefg') print 'extendleft:', d d.appendleft('h') print 'appendleft:', d
$ python collections_deque_populating.py
extend: deque(['a', 'b', 'c', 'd', 'e', 'f', 'g'])
append: deque(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
extendleft: deque(['g', 'f', 'e', 'd', 'c', 'b', 'a'])
appendleft: deque(['h', 'g', 'f', 'e', 'd', 'c', 'b', 'a'])
import collections
print 'From the right:'
d = collections.deque('abcdefg')
while True:
try:
print d.pop()
except IndexError:
break
print '\nFrom the left:'
d = collections.deque('abcdefg')
while True:
try:
print d.popleft()
except IndexError:
break
$ python collections_deque_consuming.py From the right: g f e d c b a From the left: a b c d e f g
extendleft(list): This function is similar to extend(), but it reverses the list of values passed as the argument and then appends that list to the left end of the deque.,A deque is a double-ended queue in which elements can be both inserted and deleted from either the left or the right end of the queue. An implementation of a deque in Python is available in the collections module.,extend(list): This function is used to insert multiple values at the right end. It takes a list of values as an argument.,index(e, start, end): Search the given element from start to finish and return the index of the first occurrence.
# Import collections module:
import collections
# Initialize deque:
dq = collections.deque([4, 5, 6])
# Append to the right:
dq.append(7)
print("Append 7 to the right: ", list(dq))
# Append to the left:
dq.appendleft(3)
print("Append 3 to the left: ", list(dq))
# Append multiple values to right:
dq.extend([8, 9, 10])
print("Append 8, 9 and 10 to the right: ", list(dq))
# Append multiple values to left:
dq.extendleft([1, 2])
print("Append 2 and 1 to the left: ", list(dq))
# Insert - 1 at index 5
dq.insert(5, -1)
print("Insert -1 at index 5: ", list(dq))
# Pop element from the right end:
dq.pop()
print("Remove element from the right: ", list(dq))
# Pop element from the left end:
dq.popleft()
print("Remove element from the left: ", list(dq))
# Remove - 1:
dq.remove(-1)
print("Remove -1: ", list(dq))
# Count the number of times 5 occurs:
i = dq.count(5)
print("Count the number of times 5 occurs: ", i)
# Return index of '7'
if found between index 4 and 6:
i = dq.index(7, 4, 6)
print("Search index of number 7 between index 4 and 6: ", i)
# Rotate the deque three times to the right:
dq.rotate(3)
print("Rotate the deque 3 times to the right: ", list(dq))
# Reverse the whole deque:
dq.reverse()
print("Reverse the deque: ", list(dq))
Author: Aditya Raj Last Updated: June 8, 2021
To use deque in python, we will first import the module using the import statement as follows.
from collections
import deque
from collections
import deque
myDeque = deque([1, 2, 3, 4, 5])
print("The created deque is:")
print(myDeque)
Output:
The created deque is:
deque([1, 2, 3, 4, 5])
To insert an element at the end of the deque, we can use the append() method. The append() method takes an element as input when it is invoked on a deque object and adds the element to the end of the deque. This can be seen in the following example.
print("Deque before insertion:")
print(myDeque)
myDeque.append(6)
print("Deque after insertion of element 6 at end:")
print(myDeque)
We can also insert multiple items at the same time into a deque. To insert multiple elements at the start of a deque, we can use extendleft() method. The extendleft() method takes an iterable such as list or tuple as input when it is invoked on a deque and adds the elements to the start of the deque in reversed order as that of passed in the input as follows.
print("Deque before insertion:")
print(myDeque)
myDeque.extendleft([-2, -3, -4])
print("Deque after insertion of multiple elements at start:")
print(myDeque)
If maxlen is not specified or is None, deques may grow to an arbitrary length. Otherwise, the deque is bounded to the specified maximum length. Once a bounded length deque is full, when new items are added, a corresponding number of items are discarded from the opposite end. Bounded length deques provide functionality similar to the tail filter in Unix. They are also useful for tracking transactions and other pools of data where only the most recent activity is of interest.,Returns a new deque object initialized left-to-right (using append()) with data from iterable. If iterable is not specified, the new deque is empty.,Deques are a generalization of stacks and queues (the name is pronounced “deck” and is short for “double-ended queue”). Deques support thread-safe, memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction.,Though list objects support similar operations, they are optimized for fast fixed-length operations and incur O(n) memory movement costs for pop(0) and insert(0, v) operations which change both the size and position of the underlying data representation.
Changed in version 2.6: Added maxlen parameter.
>>> from collections import deque >>> d = deque('ghi') # make a new deque with three items >>> for elem in d: # iterate over the deque's elements ... print elem.upper() G H I >>> d.append('j') # add a new entry to the right side >>> d.appendleft('f') # add a new entry to the left side >>> d # show the representation of the deque deque(['f', 'g', 'h', 'i', 'j']) >>> d.pop() # return and remove the rightmost item 'j' >>> d.popleft() # return and remove the leftmost item 'f' >>> list(d) # list the contents of the deque ['g', 'h', 'i'] >>> d[0] # peek at leftmost item 'g' >>> d[-1] # peek at rightmost item 'i' >>> list(reversed(d)) # list the contents of a deque in reverse ['i', 'h', 'g'] >>> 'h' in d # search the deque True >>> d.extend('jkl') # add multiple elements at once >>> d deque(['g', 'h', 'i', 'j', 'k', 'l']) >>> d.rotate(1) # right rotation >>> d deque(['l', 'g', 'h', 'i', 'j', 'k']) >>> d.rotate(-1) # left rotation >>> d deque(['g', 'h', 'i', 'j', 'k', 'l']) >>> deque(reversed(d)) # make a new deque in reverse order deque(['l', 'k', 'j', 'i', 'h', 'g']) >>> d.clear() # empty the deque >>> d.pop() # cannot pop from an empty deque Traceback (most recent call last): File "<pyshell#6>", line 1, in -toplevel- d.pop() IndexError: pop from an empty deque >>> d.extendleft('abc') # extendleft() reverses the input order >>> d deque(['c', 'b', 'a'])