Python list insert() method is used to insert an element to the list at the specified index.
Syntax
list.insert(index, element)
Parameters
- index(required) – It is the position where an element needs to be inserted.
- element(required) – It is the element to be inserted in the list.
Return value
This method doesn’t return anything; returns None. It only updates the current list.
Example 1: How to Use List insert() Method
GoT = ['Daenerys', 'Jon', 'Tyrion']
GoT.insert(1, 'Varys')
print(GoT)
Output
['Daenerys', 'Varys', 'Jon', 'Tyrion']
Example 2: Inserting a Tuple (as an Element) into the List
GoT1_list = ['Daenerys', 'Jon', 'Tyrion']
Friends1_tuple = ('Rachel', 'Monica', 'Phoebe')
GoT1_list.insert(2, Friends1_tuple)
print(GoT1_list)
Output
['Daenerys', 'Jon', ('Rachel', 'Monica', 'Phoebe'), 'Tyrion']
Example 3: AttributeError: ‘str’ object has no attribute ‘insert’
If we try to insert anything in a string because the string doesn’t have attribute insert().
# AttributeError
string = "192111"
string.insert(10, 1)
print(string)
Output
AttributeError: 'str' object has no attribute 'insert'
Example 4: Insert in a List Before any Element
listA = [11, 21, 19, 46, 18]
# Element to be inserted
element = 20
# Element to be inserted before 3
beforeElement = 46
# Find index
index = listA.index(beforeElement)
# Insert element at beforeElement
listA.insert(index, element)
print(listA)
Output
[11, 21, 19, 20, 46, 18]
Example 5: Adding an Element to the Beginning of a List
data = ['bmw', 'audi', 'mercedez']
data.insert(0, 'jaguar')
print(data)
Output
['jaguar', 'bmw', 'audi', 'mercedez']
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.