Python List insert method with Example – Python Tutorial

1 year ago Lalit Bhagtani 0

In this tutorial, we will learn about python list insert method.
Python List Insert

insert method :

This method is used to insert an element ( item passed as an second argument ) at the specific index ( index passed as a first argument ) of the given list. If value of index is greater than length of the list, then item is inserted to the end of the list.

Syntax : < List Object >.insert( index, item ) 
               index : it is an index in the list, where passed item will be inserted.
               item : it is an element, which is going to be inserted in the given list.

Example:

[datacamp_exercise lang=”python” height=”520″ min-height=”200″ max-height=”500″]
[datacamp_pre_exercise_code]

[/datacamp_pre_exercise_code]
[datacamp_sample_code]
# Python List insert example
# create list object and assign it to variable l
l = [‘a’,’b’,’c’,’d’]

# call insert() method by passing 2 and ‘g’ as an argument
l.insert(1,’g’)

# print the list, to check its elements
print(l)

# call insert() method by passing 5 and ‘h’ as an argument
l.insert(5,’h’)
# in this case insert method is used as an append method because passed index value 5 is greater that length of l list.

# print the list, to check its elements
print(l)

# another way of inserting element in the list (without using insert() method)
l[3:3] = ‘j’

# print the list, to check its elements
print(l)
[/datacamp_sample_code]
[datacamp_solution]

[/datacamp_solution]
[/datacamp_exercise]

References :-

  1. insert method Docs

That’s all for Python List insert method. If you liked it, please share your thoughts in comments section and share it with others too.

Previous