89DEVs

Python List insert()

python list insert()

The insert() method of Python Lists inserts a given element at a given index.

insert at start of list

To insert am element at the start of the given list, use the argument index=0 as shown below. # insert element at start of list list1 = [2, 3, 4] list1.insert(0, 1) print(list1) In this example, the list1 contains the integer values 2, 3 and 4. The insert() method is called to insert the integer value 1 at index 0, which is the start of the list. Finally, the list1 is printed and the result is shown below. The list contains integer values 1, 2, 3 and 4. [1, 2, 3, 4]

insert at specific position

To insert an element at a specific position, use the insert() method as shown below. # insert element into list at specific position list1 = [1, 2, 4] list1.insert(2, 3) print(list1) In this example, the list1 contains integer values 1, 2 and 4. The insert() method is called to insert the integer value 3 at index 2, which is position 3 of the list. Finally, the list is printed and the result is a list with integer values 1, 2, 3 and 4. [1, 2, 3, 4]

syntax of insert()

The syntax of the List insert() method is: list.insert(index, element)

arguments of insert()

The insert() method accepts exactly two parameters, both are needed. The index defines where the element is inserted. Like usual Python starts the index at 0. The element to be inserted into the list.

return value of insert()

The insert() returns None. The given list is updated and the specified element is inserted at the specified index.

                
        

Summary


Click to jump to section