Pyhton list insert() method

In Python the list insert() method can insert any elements at any position inside the list object.To make the insertion of elements in any possible the insert() method will accept two arguments.

The first argument is the position in which the element is to be inserted.If you want to insert element at 1st position then pass 1.Note the counting always start form 0.
The second argument is the element to be inserted.

>> ls=['True', 'False']
>>> ls.insert(1 , 'nuetral') 
>>> ls
['True', 'nuetral', 'False']
>>> #inserting list object
>>> ls.insert( 2 , [1 , 2 , '3'] )
>>> ls
['True', 'nuetral', [1, 2, '3'], 'False']

Well it is not hard to understand what insert() method really does.

Point to note

To insert element at the end of the list object we will utilize the first argument at ‘len( ls )’,here ‘ls’ is the list object to which the element is to inserted and ‘len(ls)’returns the number of elements in the ‘ls’ lis object.

>>>  ln=[5.6007 , '9.008' , 12.45008 ]
>>> ln.insert(len(ln), 34.56)
>>> ln
[5.6007, '9.008', 12.45008, 34.56]
>>> #inserting tuple
>>> ln.insert( len(ln) , ('C' , '+' , '+'))
>>> ln
[5.6007, '9.008', 12.45008, 34.56, ('C', '+', '+')]

Note inserting element at the end of the list object is also performed by the append() method so the expression ‘ls.insert( len(ls), x)’ is equivalent to ‘ls.append(x)’.

Link :list append method

Leave a Reply

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