extend() method to add iterable to list

All list methods

extend(iterable) takes one argument.

More about iterable objects.
my_list1=['Alex','Ronald','John']
my_list2=['Ravi','Alen']
my_list1.extend(my_list2)
print(my_list1)
Output
['Alex', 'Ronald', 'John', 'Ravi', 'Alen']

Using string as iterable object

In above code we used one more list to add the elements to our main list. Here we will try with string ( string is an iterable object )
my_list1=['a','b','c','d']
str='xyz'  # string 
my_list1.extend(str) 
print(my_list1)
Output
['a', 'b', 'c', 'd', 'x', 'y', 'z']
To add only one element we will use append. To add the elements of another list ( or 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']
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