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'
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.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

Using integers only

[1, 5, 22, 2, 3]
Using len() to check the length of the list
print("Length before append : ",len(my_list))
print("Length after append : ",len(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

Post your comments , suggestion , error , requirements etc here

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