Menu Close

Python List insert() Method

Python list insert() method

In this tutorial, you will learn about the Python list insert() method. The list insert function is a built-in list function that is used to insert the element on a specific position in the list.
Sometimes we need to insert a specific element on a specific position, Then we have the best list method insert() to perform that operation.

In the previous tutorial we have seen, the Python list index() method, and the Python list extend() method.

Python list insert() method:

In Python, the insert() method is a list built-in method that is used to add an element at the specific position or index number in the existing list.

List insert() method Syntax:

list.insert(position, element)

List insert() method Parameter:

The list insert method takes two parameters:

position:- Index number where the elements need to be inserted.
element:- this is the element to be inserted in the list

Return value from insert():

The insert() method does not return anything.

Note:- You have to remember the index always starts with 0.

Example of list insert() method:

In the below example, we will insert different values into the list using the list insert() method.

Example 1

#Insert a number to the 4th index number.
numbers = [12, 14, 15, 17]
numbers.insert(4, 30)
print(numbers)

Output

[12, 14, 15, 17, 30]

Example 2

#Insert a tuple to the list.
lang = ['Python', 'PHP', 'R', 'Ruby', 'Go', 'JavaScript']
new_tuple = ( 'Ruby', 'C', 'C++')
lang.insert(6, new_tuple)
print(lang)

Output

['Python', 'PHP', 'R', 'Ruby', 'Go', 'JavaScript', ('Ruby', 'C', 'C++')]

Conclusion:

In this tutorial, You have learned about the Python list insert() method to add the elements to a list at a specific position or index number.
I hope this tutorial will help you. If you like this article please comment and share it with your friend who wants to learn Python programming from scratch to advanced.

See Also:

For More Information:- Click Here

Python List index() Method
Python List pop() Method

Related Posts