9 Ways to Combine Lists in Python

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 list without any hassle.

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.

  1. Using Naïve Method to combine lists in python
  2. Using Python’s extend function
  3. The append function
  4. Using + operator
  5. List comprehension
  6. Using * Operator
  7. Using itertools.chain()
  8. Combine Lists into Python Dictionary
  9. Combine Lists in Python into Data Frame

Using Naive Method to Combine Lists in Python

A 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 Python

list1=[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]
python combine lists

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 function

Python 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.
It is lesser than the time complexity of the naïve method.
Also, we are making changes in list2, list1 will remain as it is.

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 function

Append 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.
It has a time complexity of O(1).

Using + operator

Yes. 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 comprehension

flower1=['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 * Operator

If 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'>

Using itertools.chain()

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 Dictionary

There 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 Frame

import 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 Read

Unzip a File in Python: 5 Scenarios You Should Know
Understanding Collatz Sequence in Python
Best Ways to Calculate Factorial Using Numpy and SciPy

Conclusion

We 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.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments