insert() method to add element to a list

All list methods

insert(i,x) takes two arguments .

i: the position where the element is to be added
x: the element to be added

Note : List uses 0 based indexing system so first element position is 0. Here 1 is after first position that is after 'Alex'
my_list=['Alex','Ronald','John']
my_list.insert(1,'Ravi')
print(my_list)
Output is here
['Alex', 'Ravi', 'Ronald', 'John']

Difference between Append and Insert

Using len() function we can get the total number of elements in a list. So in a zero based index system ( first element position is 0 ) we can add the element at last position by using len().
append() adds the element at the end of the list ( always) , by using insert we can add element at any given position. If we add element by using insert at the end of the list , then it is same as append().
my_list=['Alex','Ronald','John']
#my_list.append('new name') # adds at the end of the list
my_list.insert(len(my_list),'new name') # adds at the end of the list
print(my_list)

Using integers only

my_list=[1,5,2,3]
my_list.insert(2,22)
print(my_list)
Output
[1, 5, 22, 2, 3]
Using len() to check the length of the list
my_list=['Alex','Ronald','John']
print("Length before append : ",len(my_list))
my_list.append('Ravi')
print("Length after append : ",len(my_list))
print(my_list)
Output is here
Length before append :  3
Length after append :  4
['Alex', 'Ronald', 'John', 'Ravi']
All list methods Questions with solutions on List

Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here





    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2021 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer