Python List insert()

Python list‘s insert method is used to insert item at particular index


Syntax

Here list1 is object of the list.


Return

returns nothing, it just make changes to original list.


Example

Let’s see a very simple example:

l=[1,2,4] l.insert(2,3) print(l) l.insert(1,'one') print(l)

Output:

[1, 2, 3, 4]
[1, ‘one’, 2, 3, 4]

Please note that index in python starts at index 0 not from 1.
Let’s add tuple and set to the list using extend.

l=[1,2,3] t=('one','two') l.insert(2,t) print(l) t=('three') l.insert(4,t) print(l) print("List l:",l)

Output:

[1, 2, (‘one’, ‘two’), 3]
[1, 2, (‘one’, ‘two’), 3, ‘three’]

That’s all about Python List insert() method.

Leave a Reply

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