append() method to add element to list

All list methods

append() takes exactly one argument ( not more than one ) and adds at the end of the list.
my_list=['Alex','Ronald','John']
my_list.append('Ravi')
print(my_list)
Output is here
['Alex', 'Ronald', 'John', 'Ravi']

Appending one more list

What is the difference between append() and extend() ?
Using append to add a list
my_list=['Alex','Ronald','John']
my_list2=['Ravi','John','Ronald']
my_list.append(my_list2)
print(my_list)
Output is here
['Alex', 'Ronald', 'John', ['Ravi', 'John', 'Ronald']]
In the above code the list is added at the end of my_list. To add only the elements of another list ( any iterable ) we can use extend(). This is the difference between append and extend methods.
my_list=['Alex','Ronald','John']
my_list2=['Ravi','John','Ronald']
my_list.extend(my_list2)
print(my_list)
Output is here
['Alex', 'Ronald', 'John', 'Ravi', 'John', 'Ronald']

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.

Adding at the end of the list

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


plus2net.com



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 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer