In this section, we will learn what the List extend() method is and how to use it in Python.
What is Python List extend() Method?
The Python list extend() method is used to add the entire elements of another list or any other iterable object to the end of the list that is invoking this method.
Note: the operation that extend() method runs is a shallow copy! Please check the Python List Copy section in order to learn more about shallow copy.
List extend() Method Syntax:
List extend() Method Parameter:
The method takes one argument, and that is a reference to an iterable object (like a list) that we want to add their elements to the end of the list that is invoking this method.
List extend() Method Return Value:
The method does not return a value.
Example: python extend list
li = ["ItemOne","ItemTwo","ItemThree","ItemOne","ItemTwo","ItemThree"] list2 = [1,2,3,4,5,6] tup = (7,8,9,10) li.extend(list2) li.extend(tup) print(li)
['ItemOne', 'ItemTwo', 'ItemThree', 'ItemOne', 'ItemTwo', 'ItemThree', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Example: Python extend() method and shallow copy
list1 = [1,2,3,4] list2 = [ ["Jack","John","Omid"],1,2,3,4 ] list1.extend(list2) list1 = "Elon" print(list1) print(list2)
[1, 2, 3, 4, ['Elon', 'John', 'Omid'], 1, 2, 3, 4] [['Elon', 'John', 'Omid'], 1, 2, 3, 4]