Python List insert()

Previous
Next

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

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.

listOfItems=['Book','Table','TV'] listOfItems.insert(1,'Chair') print(listOfItems)

Output:

[‘Book’, ‘Chair’, ‘Table’, ‘TV’]

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.

listOfItems=['Book','Table','TV'] listOfItems.insert(2,('Car','Cycle')) print(listOfItems)

Output:

[‘Book’, ‘Table’, (‘Car’, ‘Cycle’), ‘TV’]

That’s all about Python List insert method.

Previous
Next

Join Our News Letter – Stay Updated

Subscribe to Awesome Java Content.




Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog