One of the most important data structures used in Python is a list. It has various use cases in Python as it is mutable, can contain values of any other data type in the same list. Also, we can have an element with equal value more than once (which is not possible in sets) and is backed by many different methods, which makes our life a lot easier. In Python, we can combine multiple lists into a single listwithout any hassle. Show
Table of Contents
Table of Contents
In this article, let us explore multiple ways to achieve the concatenated lists. Some other standard terms are concatenating the list, merging the list, and joining the list.
Using Naive Method to Combine Lists in PythonA naive method is a method that comes first to mind when thinking about how to perform a particular task. It is not optimized and generally has greater time complexity than other methods. We will use a for loop for combining two lists- list1=[1,2,3,4] list2=[5,6,7,8] for i in list2: # appending the elements of list2 into list1 list1.append(i) print(list1) Output- [1, 2, 3, 4, 5, 6, 7, 8] Combining more than two lists in Pythonlist1=[1,2,3,4] list2=[5,6,7,8] list3=[9,10,11,12] for i in list2: # appending the elements of list2 into list1 list1.append(i) for i in list3: # appending the elements of list3 into list1 list1.append(i) print(list1) Output- [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] You may be thinking that what a simple method this is. So why we don’t usually use this method and call it as naïve. The answer is simple, we are using two for loops here, and if we have many lists and, in those lists, we have many elements, how great the time complexity will be! That is why we have different methods for the purpose. Using Python’s extend functionPython has a built-in function for this purpose- extend. Let us see how this works- list1=[1,2,3,4] list2=[5,6,7,8] list2.extend(list1) print(list2) Output- [5, 6, 7, 8, 1, 2, 3, 4] You can better understand the working of this function with the following code- list1=[1,2,3,4] list2=[5,6,7,8] list2[len(list2):]=list1 print(list2) Output- [5, 6, 7, 8, 1, 2, 3, 4] The time complexity of this extend() function is O(k), where k is the length of the list we need to
concatenate to another list. list1=[1,2,3,4] list2=[5,6,7,8] list2[len(list2):]=list1 print("list2",list2) print("list1",list1) Output- list2 [5, 6, 7, 8, 1, 2, 3, 4] list1 [1, 2, 3, 4] Using the append functionAppend function can be used to add one complete list to another list. It means the elements will not be added one by one but the complete list will be added on the same index. Don’t worry if you don’t understand. We will understand it with an example. list1=[1,2,3,4 list2=[5,6,7,8] list1.append(list2) print(list1) Output- [1, 2, 3, 4, [5, 6, 7, 8]] You would have surely noticed the change from the previous output. Using + operatorYes. You read it right. We can concatenate any lists using the + operator. list1=[1,2,3,4] list2=[5,6,7,8] list3=[9,10,11,12] list4= list1+list2+list3 print(list4) Output- [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] The difference between this method and other methods we have learned till now is that in this method, we are concatenating three different lists in another list. In all the previous ways, the change was taking place in one of the lists. Using list comprehensionflower1=['sunflower','lotus','rose'] flower2=['marigold','lily','tulip' flowers=[y for x in (flower1,flower2) for y in x] print(flowers) Output- ['sunflower', 'lotus', 'rose', 'marigold', 'lily', 'tulip'] Using * OperatorIf you have never used * operator in a list or other data types like tuple, you will be glad to know how useful an operator it is. It is used for unpacking the list. For example- list1=[1,2,3,4,5] print(*list1) Output- 1 2 3 4 5 Isn’t it lovely? I personally find this operator very useful. Now let us see how * operator can be used to combine different lists in python. list1=[1,2,3,4,5] list2=[6,7,8,9] list3=[list1,list2] print(list3) Output- [1, 2, 3, 4, 5, 6, 7, 8, 9] If we want, we can use this to combine different lists into a tuple or a set as well. list1=[1,2,3,4,5] list2=[6,7,8,9] new_tuple=list1,list2 print(new_tuple) print("type: ",type(new_tuple)) Output- (1, 2, 3, 4, 5, 6, 7, 8, 9) type: <class 'tuple'> list1=[1,2,3,4,5] list2=[6,7,8,9] new_set={list1,list2} print(new_set) print("type: ",type(new_set)) Output- {1, 2, 3, 4, 5, 6, 7, 8, 9} type: <class 'set'> We can import the itertools package of python and use its chain function to combine lists. To import use – from itertools import chain from itertools import chain list1=[1,2,3,4,5] list2=[6,7,8,9] list3=list(chain(list1,list2)) print(list3) Output- [1, 2, 3, 4, 5, 6, 7, 8, 9] As we know that itertools returns an object so we first have to typecast it into list data type and then print it. Combine Lists into Python DictionaryThere are so many methods to convert two lists into a dictionary as a key value, but we will only study here the most common and efficient way. names=["ashwini","ashish","arya"] marks=[40,47,32] student_info=dict(zip(names,marks)) print(student_info) Output- {'ashwini': 40, 'ashish': 47, 'arya': 32} Combine Lists in Python into Data Frameimport pandas as pd list1=[1,2,3,4,5] list2=[6,7,8,9,10] df1=pd.DataFrame(list1,columns=["Values"]) df2=pd.DataFrame(list2,columns=["Values"]) final_df=pd.concat((df1,df2)) print(final_df) Output- Values 0 1 1 2 2 3 3 4 4 5 0 6 1 7 2 8 3 9 4 10 Suppose if we want to combine these two list2 in different columns of a Data Frame-import pandas as pd list1=[1,2,3,4,5] list2=[6,7,8,9,10] df=pd.DataFrame(columns=['list1','list2']) df['list1'],df['list2']=list1,list2 print(df) Output- list1 list2 0 1 6 1 2 7 2 3 8 3 4 9 4 5 10 Must ReadUnzip a File in Python: 5 Scenarios You Should Know ConclusionWe have studied so many methods using which we can combine multiple lists in Python. You should any of them according to your needs. We have considered how to combine those lists in the form of the data frame, sets, tuples, and in the form of key and value pairs in the dictionary. Please let us know in the comment section if you use any other methods. How do you combine two lists in Python?In python, we can use the + operator to merge the contents of two lists into a new list. For example, We can use + operator to merge two lists i.e. It returned a new concatenated lists, which contains the contents of both list_1 and list_2. How do you join 3 lists in Python?Join multiple lists in Python. Using + operator. Python supports list operations like concatenation with the help of the + operator. ... . Using itertools. chain() function. ... . Using Iterable Unpacking Operator. You can also use the * iterable unpacking operator to join multiple lists. ... . Using list. extend() function.. How do you combine lists within a list Python?Use the sum() function to concatenate nested lists to a single list by passing an empty list as a second argument to it. How do you mix two lists?This operation is useful when we have numbers of lists of elements which needs to be processed in a similar manner.. Method #1 : Using Naive Method.. Method #2 : Using + operator.. Method #3 : Using list comprehension.. Method #4 : Using extend(). Method #5 : Using * operator.. Method #6 : Using itertools.chain(). |