Insert() Method Of Deque Class In Python

Method Name:



Method Signature:

insert(index, elem)


Method Overview:

  • insert() method inserts an element specified by the elem parameter into the position specified by the index parameter.


  • On a fixed length deque object which already has reached its maximum size calling insert() raises an exception of type IndexError.


  • As with any container in Python, if the index specified is a negative value the index is counted from the right end of the deque.


  • When a positive index is specified as a parameter to the insert() method if the index is greater than or equal to the length of the queue, the element is inserted next to the highest index.


  • When a negative index is specified as a parameter to insert() if the index is less than zero and reaches past index zero from the right side of the deque, the element is inserted at position zero.




import collections


# A tuple of player numbers

players         = ("p1", "p2", "p3", "p4")


# A deque created out of players tuple

playersDeque    = collections.deque(players)


#Regular case now

playersDeque.insert(0, "p0")



#Inserting at an index greater than or equal to the length will insert at the last


playersDeque.insert(10, "px")



# Inserting at an index less than zero and if the index goes past zero,

# will insert at the index zero

playersDeque.insert(-9, "py")




deque(['p0', 'p1', 'p2', 'p3', 'p4'])

deque(['p0', 'p1', 'p2', 'p3', 'p4', 'px'])

deque(['py', 'p0', 'p1', 'p2', 'p3', 'p4', 'px'])



Copyright 2023 ©