To insert an element at a specific index in a list in Python, you can use the insert
method.
In this example,
numbers
with initial integer values.insert
method to insert a new element at the desired index.insert
method shifts the existing elements to the right to make space for the new element.numbers = [1, 2, 3, 4, 5]
numbers.insert(2, 10)
print('Updated list:', numbers)
Updated list: [1, 2, 10, 3, 4, 5]
In this example,
numbers
with initial integer values.numbers = [1, 2, 3, 4, 5]
index = 2
element = 10
updated_list = numbers[:index] + [element] + numbers[index:]
print('Updated list:', updated_list)
Updated list: [1, 2, 10, 3, 4, 5]
In this tutorial, we learned How to Insert an Element at Specific Index in a List in Python language with well detailed examples.