In this Python tutorial, you will learn how to use list.insert()
method to insert an element at given index, and explaining different use cases with insert() method in detail with example programs.
Python List Insert
Python list.insert(index, element) method inserts the element at a given index in the list.
Syntax
The syntax of to call insert() method on a list myList
is
myList.insert(index, element)
where
- myList is a Python List.
- insert is the list method name.
- index is the position at which we would to make an insertion.
- element is the object we insert at given index.
insert() method modifies the original list that we are calling upon, and returns None.
Examples
1. Insert element at given index in the list
In this example, we will take a list of strings, and insert an element at index 2.
The following picture depicts how insert operation works. The method inserts the element at the given index and pushes the elements to their next positions.
main.py
myList = ['apple', 'banana', 'cherry', 'orange']
myList.insert(2, 'mango')
print(myList)
Output
['apple', 'banana', 'mango', 'cherry', 'orange']
2. Insert element at start of the list
In this example, we will use insert() method to insert element in the list at starting position. All the elements of the list are shifted by one position. The index for first element is 0, and so we shall pass 0 as the first argument, and the element as the second argument.
main.py
myList = ['apple', 'banana', 'cherry', 'orange']
myList.insert(0, 'mango')
print(myList)
Output
['mango', 'apple', 'banana', 'cherry', 'orange']
3. Insert element at end of the list
In this example, we will insert the element at end of the list. The result would be similar to append() method.
To insert the element at the end of the list, the index that has to be passed as first argument would be the length of the list.
main.py
myList = ['apple', 'banana', 'cherry', 'orange']
myList.insert(len(myList), 'mango')
print(myList)
Output
['apple', 'banana', 'cherry', 'orange', 'mango']
insert() method – Time Complexity
The time complexity to insert an element at a given index is O(n). This means that the complexity increases linearly with the number of elements in the list.
Conclusion
In this Python Tutorial, we have learned the syntax of list.insert() method and its usage with the help of example programs.