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.


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

# 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

# print the list, to check its elements

# call insert() method by passing 5 and ‘h’ as an argument
# 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

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

# print the list, to check its elements


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.