Click for All Topics
.extend()
method with a list and pass an iterable as an argument then it iterates over the elements of the iterable and add elements of iterable one by one to the end of the list.+
operator in place of .extend()
method .
Syntax –
list.extend(iterable)
Parameter –
Example 1- Extend a list to the list
my_list1=[11,22,33,44,55]
print("Original list: ",my_list1)
my_list2=[66,77,88,99,110]
my_list1.extend(my_list2)
print("Modified list: ",my_list1)
# Output -
# Original list: [11, 22, 33, 44, 55]
# Modified list: [11, 22, 33, 44, 55, 66, 77, 88, 99, 110]
.extend()
method.
Example 2 – extend a list with a string
lst=['a','b','c','d','e']
my_string='fgh'
print("Original list:",lst)
lst.extend(my_string)
print("Modified original list:",lst)
# Output -
# Original list: ['a', 'b', 'c', 'd', 'e']
# Modified original list: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
Example 3- extend a list with a tuple
subject=['Hindi','English','Math']
subject_tuple=('Chemistry','Physics')
print("Original subject list: ",subject)
subject.extend(subject_tuple)
print("Modified subject list: ",subject)
# Output -
# Original subject list: ['Hindi', 'English', 'Math']
# Modified subject list: ['Hindi', 'English', 'Math', 'Chemistry', 'Physics']
Example 4- extend a list to the list using +
operator
my_lst1=['hello','Python','this']
my_lst2=['is','edSlash']
print("Original list: ",my_lst1)
my_lst1=my_lst1+my_lst2
print("Modified Original list: ",my_lst1)
# Output -
# Original list: ['hello', 'Python', 'this']
# Modified Original list: ['hello', 'Python', 'this', 'is', 'edSlash']
extend() | append() |
---|---|
It adds all elements of the iterable to the list | it adds only single element to the list |
If we pass a list as an argument to extend then it adds all elements of the list to the original list | If we pass a list as an argument then it adds list itself to the original list as a nested list |
It is useful when you want to add all elements of one list to another list. | It is useful when you want to add a single element to the list or you want to add list as a single element to the list. |
Office:- 660, Sector 14A, Vasundhara, Ghaziabad, Uttar Pradesh - 201012, India