insert() method of deque class in Python

The insert() method of Python deque class inserts an element specified by the index parameter into a deque instance. An IndexError is raised if the deque is of fixed size.

Deque Updated 19 Mar 2017 1 min read

Method name

insert

Method signature

insert(index, elem)

Method Overview

  • The 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 deque, 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.

Example

python
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")

print(playersDeque)

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

#position

playersDeque.insert(10, "px")

print(playersDeque)

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

# will insert at the index zero

playersDeque.insert(-9, "py")

print(playersDeque)

Output

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

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

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