Join Regular Classroom : Visit ClassroomTech

insert() method in Python List

It is a method in list that inserts an element to a specific given index in the list. It modifies the current list.

Syntax:

list.insert(position, element)

Don’t know what is index method in python? Read: index() method in Python List

Example:

s = ["Name", "codewindow", "Country", "India"]
s.insert(2, "Website")
print(s)

Output:

[‘Name’, ‘codewindow’, ‘Website’, ‘Country’, ‘India’]

Explanation:

Here the method inserts the element “Website” at index 2 of the original list.

Example 2:

s = [2, 8, 7, 9, 33, 45, 52]
s.insert(1, 188)
print(s)

Output:

[2, 188, 8, 7, 9, 33, 45, 52]

Explanation:

Here the method inserted “188” at index 1.

Example 3:

s = [2, 8, 7, 9, 33, 45, 52]
s.insert(10, 188)
print(s)

Output:

[2, 8, 7, 9, 33, 45, 52, 188]

Explanation:

Here there is no index as 10 therefore it adds “188” to the end of the list.


You Missed

Also Checkout