ScanSkill

insert

insert() function or method is used in python list to insert an item at a given position.

Syntax

list.insert(index, object)

Here,

  • index: Required. The index of the element before which to insert.
  • object: Required. The item to insert.

Note: object(or element) will be inserted into the list at the index position. All the elements after the object(or element) will be shifted to the right. (index starts from 0, i.e. beginning of the list is 0th index)

Examples

>>> list1 = [1, 2]
>>> list1.insert(0, 0)
>>> list1
[0, 1, 2]
>>> list1.insert(2, 1.5)
>>> list1
[0, 1, 1.5, 2]
  • Tuple as an object or element
>>> list1 = [{1, 2, 3}, [1, 2, 3]]
>>> tuple1 = (1, 2, 3)
>>> list1.insert(1, tuple1)
>>> list1
[{1, 2, 3}, (1, 2, 3), [1, 2, 3]]

Here, tuple1 is inserted into 1st position, which is second in list1.

See also

extend() and append()