List insert() Method in Python

Python List insert() Method

In Python, the insert() method is used to insert an element at a specified index in a list. It is a built-in method available for lists in Python.

Syntax of the insert() method:

list_name.insert(index, element)
  • list_name: This is the name of the list in which you want to insert the element.
  • index: This is the index where you want to insert the element. The element will be inserted before the element currently at that index.
  • element: This is the value you want to insert into the list.

After inserting the element, all elements to the right of the specified index will be shifted to the right to make space for the new element.

Example 1:

# Create a list
numbers = [1, 2, 3, 4, 5]

# Insert the element 10 at index 2
numbers.insert(2, 10)

print(numbers)  # Output: [1, 2, 10, 3, 4, 5]

Example 2:

# Create a list
fruits = ['apple', 'banana', 'orange']

# Insert the element 'grapes' at index 1
fruits.insert(1, 'grapes')

print(fruits)  # Output: ['apple', 'grapes', 'banana', 'orange']

Example 3:

# Create an empty list
my_list = []

# Insert elements at specific indices
my_list.insert(0, 'a')
my_list.insert(1, 'b')
my_list.insert(2, 'c')

print(my_list)  # Output: ['a', 'b', 'c']

As you can see, the insert() method allows you to add elements at specific positions within a list, and it modifies the original list in place.