Table of Contents
In this tutorial, we will see about Python List‘s insert method.Python List insert method is used to insert element to the specified index in the list.
Python List insert syntax
1 2 3 |
list1.insert(index, element) |
here list1 is object of list.
list1.insert(1, ‘hello’): This code will add ‘hello’ string to 1st index of list1.Please note that Python index starts from 0 rather than 1.
Python List insert example
You can simply use insert method to add the element to the list at specified index.
Let’s understand this with the help of simple example.
1 2 3 4 5 |
listOfItems=['Book','Table','TV'] listOfItems.insert(1,'Chair') print(listOfItems) |
Output:
As you can see with the output, ‘Chair’ string is added to listOfItems at 1st index.
You can add set, tuple to the list using insert method.Let’s see this with the help of example.
1 2 3 4 5 |
listOfItems=['Book','Table','TV'] listOfItems.insert(2,('Car','Cycle')) print(listOfItems) |
Output:
That’s all about Python List insert method.