Python List insert() Method

The insert() method in Python is a built-in function used to insert an element at a specified index in a list. The method modifies the list in place, meaning that it adds the element to the specified position and does not return a new list. In this article, you will learn how to use the insert() method with examples.

Syntax

list.insert(index, element)

Parameters

  • index: The position in the list where the element should be inserted.
  • element: The element to be inserted in the list.

Examples

Example 1: Insert an Element at the Beginning of a List

Let’s consider a list and try to insert an element at the beginning of the list using the insert() method:

>>> a = ["dog", "cat", "horse"]
>>> a.insert(0, "bird")
>>> print(a)
['bird', 'dog', 'cat', 'horse']

In this example, we have created a list a containing three elements. We have used the insert() method to insert the element “bird” at index 0, which is the beginning of the list. Finally, we have printed the list a, which now contains four elements with the element “bird” at the beginning.

Example 2: Insert an Element at a Specific Position in a List

You can also insert an element at a specific position in the list:

>>> a = ["dog", "cat", "horse"]
>>> a.insert(1, "bird")
>>> print(a)
['dog', 'bird', 'cat', 'horse']

In this example, we have used the insert() method to insert the element “bird” at index 1, which is the second position in the list. Finally, we have printed the list a, which now contains four elements with the element “bird” at the second position.

Example 3: Insert an Element at the End of a List

You can also insert an element at the end of the list:

>>> a = ["dog", "cat", "horse"]
>>> a.insert(len(a), "bird")
>>> print(a)
['dog', 'cat', 'horse', 'bird']

In this example, we have used the insert() method to insert the element “bird” at index len(a), which is the end of the list. Finally, we have printed the list a, which now contains four elements with the element “bird” at the end.

Conclusion

In this article, you have learned how to use the insert() method in Python to insert an element at a specified index in a list. This method modifies the list in place and does not return a new list. You have seen three examples that demonstrate how to insert an element at the beginning, a specific position, and the end of a list. Understanding the insert() method is an important part of working with lists in Python, and I hope this article has helped you gain a deeper understanding of this method.

Leave a Reply

Your email address will not be published. Required fields are marked *