Python List insert()
Python List insert() method inserts a given element at a given index in a list using Python.
Python List insert() Syntax
Syntax: list_name.insert(index, element)
Parameters:
- index: the index at which the element has to be inserted.
- element: the element to be inserted in the list.
Returns: Does not return any value.
Python List insert() Example
Python insert() methods with string in Python.
Python3
lis = ['Geeks', 'Geeks']lis.insert(1, "For")print(lis) |
Output:
['Geeks', 'For', 'Geeks']
Example 1: Inserting an Element into the List
Here, we are inserting 10 at the 5th position(4th index) in a Python list.
Python3
list1 = [ 1, 2, 3, 4, 5, 6, 7 ] # insert 10 at 4th index list1.insert(4, 10) print(list1) |
Output:
[1, 2, 3, 4, 10, 5, 6, 7]
Example 2: Error of insert() Method
Here, we are inserting 1 at the 10th position in a Python list, we will get an error, If we try to insert anything in a string because the string doesn’t have attribute insert().
Python3
# attribute errorstring = "1234567" string.insert(10, 1)print(string) |
Output:
Traceback (most recent call last):
File "/home/2fe54bd8723cd0ae89a17325da8b2eb5.py",
line 7, in
string.insert(10, 1)
AttributeError: 'str' object has no attribute 'insert'Example 3: Insertion in a List Before any Element
Here, we are inserting 13 at the 3rd position before 3 in a Python list.
Python3
# Python3 program for Insertion in a list # before any element using insert() method list1 = [ 1, 2, 3, 4, 5, 6 ] # Element to be inserted element = 13 # Element to be inserted before 3beforeElement = 3 # Find indexindex = list1.index(beforeElement) # Insert element at beforeElement list1.insert(index, element) print(list1) |
Output:
[1, 2, 13, 3, 4, 5, 6]
Example 4: Inserting a Tuple into the List
Here we are inserting a tuple in a list using the insert() function in Python.
Python3
list1 = [ 1, 2, 3, 4, 5, 6 ] # tuple of numbersnum_tuple = (4, 5, 6) # inserting a tuple to the listlist1.insert(2, num_tuple) print(list1) |
Output:
[1, 2, (4, 5, 6), 3, 4, 5, 6]


Please Login to comment...