The list method extend() used to add the specified list elements (or any iterable) to the end of the current list. It expects an iterable object as parameter to extend the current list elements.
1 <list>.extend(<iterable>)
list : A list object to add specified iterable object element
iterable : An iterable object whose elements will be added to the list object, it can be list, set, tuple, etc.
List method extend()
1 list1 = [1, 2, 3]
2 list2 = [4, 5, 6]
3
4 print('List 1 :', list1)
5 print('List 2 :', list2)
6
7 list1.extend(list2)
8 print('A resulting list 1 :', list1)
In the above example, a list of numbers are created and print original list. A list method extend() called by specifying a list object that appends a specified list element in the source list.
1 List 1 : [1, 2, 3]
2 List 2 : [4, 5, 6]
3 A resulting list 1 : [1, 2, 3, 4, 5, 6]
List with different data type
1 numbers = [1, 2, 3, 2]
2 fruits = ['apple', 'banana', 'mango']
3
4 print("Numbers list : ", numbers)
5 print("Fruits list : ", fruits)
6
7
8 numbers.extend(fruits)
9 print("Extended number list ", numbers)
In the above example, a list objects created by specifying numbers and strings. A list objects are printed on console that prints initial list elements. A method extend() called for number by specifying fruits list which will extends numbers list and print extended list on console.
1 Numbers list : [1, 2, 3, 2]
2 Fruits list : ['apple', 'banana', 'mango']
3 Extended number list [1, 2, 3, 2, 'apple', 'banana', 'mango']
Related options for your search