Python List insert() Method



The Python List insert() method inserts an object into a list at a specified position. Once the insertion of an element is done, the succeeding elements are shifted one place to their right and the length of the list is increased by 1.

Since a Python list is considered as a basic data structure and is accessed using the indexing technique, the time complexity of this method is O(n) where n is the number of elements in the list. That means the complexity increases linearly with the number of elements.

Syntax

Following is the syntax for the Python List insert() method −

list.insert(index, obj)

Parameters

  • index − This is the Index where an object needs to be inserted.

  • obj − This is the Object to be inserted into the given list.

Return Value

This method does not return any value. To see the results of this method, the list needs to be printed to check if the element is inserted successfully.

Example

The following example shows the usage of the Python List insert() method.

aList = [123, 'xyz', 'zara', 'abc']
aList.insert(3, 2009)
print("Final List : ", aList)

When we run above program, it produces following result −

Final List : [123, 'xyz', 'zara', 2009, 'abc']

Example

Here, if we want to insert the object at the beginning of the list, we can do so by just passing the value 0 as an index parameter to the method as shown in the example below.

aList = [123, 'xyz', 'zara', 'abc']
aList.insert(0, 456)
print("Final List : ", aList)

If we compile and run the program above, the result is produced as follows −

Final List :  [456, 123, 'xyz', 'zara', 'abc']

Example

Likewise, the object can also be added at the end of the list. To do this, index argument passed to the method must be equal to or greater than the length of this list; since a Python List follows zero-indexing technique. The method in this scenario works similar to the append() method. Let us see an example below.

aList = [123, 'xyz', 'zara', 'abc']
aList.insert(len(aList), 456)
print("Final List : ", aList)

Compile and run the program above to obtain the following output −

Final List :  [123, 'xyz', 'zara', 'abc', 456]

Example

Instead of a single element, let us try to insert another list into the existing list using the insert() method. In this example, we are first creating a list [123, 'xyz', 'zara', 'abc']. Then, this method is called on this list by passing another list and an index value as its arguments.

aList = [123, 'xyz', 'zara', 'abc']
aList.insert(2, ['2', '3', '4'])
print("Final List : ", aList)

Once we execute the program above, the final list is displayed with the list object insert into the existing list as a single object. It is shown below.

Final List :  [123, 'xyz', ['2', '3', '4'], 'zara', 'abc']

This works for other collection of elements like tuple, set, strings etc.

python_lists.htm
Advertisements