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 which 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, Python list index() method, 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:

List insert method take 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, Index always stat 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 list at a specific position or index number.
I hope this tutorial will help you. If you like this article please comment and share with your friend who wants to learn Python programming from scratch to advanced.

For More Information:- Click Here

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

Related Posts