Python List insert method with Example – Python Tutorial

3 weeks ago codedestine 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:

# 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)

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