In this section, we will learn how to concatenate a List in Python.
Python Combining Lists
Combining lists is the process of putting together two or more lists in order to create a new one that contains the elements of the entire lists involved in the operations.
There are multiple ways we can do this. But two of the famous methods are using the addition operation and the other one is the `extend()` method.
Using the addition `+` operator, we can involve two lists, take their elements and create a new one as a result. Note that using this operation, the final result (the new list) will have a shallow copy of the list’s elements. Please check the Python list copy section in order to learn more about shallow copy.
Example: python join lists using addition operator
list1 = [[1,2,3],2,3,4] list2 = [5,6,7,8,9,10] finalList = list1 + list2 finalList = 1000 print(list1) print(finalList)
[[1000, 2, 3], 2, 3, 4] [[1000, 2, 3], 2, 3, 4, 5, 6, 7, 8, 9, 10]
Python Merge Lists: extend() method
Using the `extend()` method, we can append the elements of one list to the end of another list!
Note that using the `extend()` method won’t return a new list, but instead it will modify the list object that invoked the `extend()` method!
Also, the method takes one argument, and that is the iterable object (another list for example) that we want to append its elements to the end of the list that invoked the method.
Please check the `extend() method section for more information.
Example: join two lists in python
list1 = [1,2,3,4] message = "Hi my name is John Doe" list1.extend(message) print(list1)
[1, 2, 3, 4, 'H', 'i', ' ', 'm', 'y', ' ', 'n', 'a', 'm', 'e', ' ', 'i', 's', ' ', 'J', 'o', 'h', 'n', ' ', 'D', 'o', 'e']
Note: the `extend()` method also runs a shallow copy!
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]