Join Multiple Lists in Python
Lists in Python are so powerful data structures. The list is a collection that is ordered or changeable.
Here we are going to see how to merge or join multiple lists in Python. Merging a list can be useful in data science or Machine Learning applications. It can also be sometimes useful in web development It can be done by a few simple approaches mentioned below :
- Use of ‘+’ operator :
By simply adding two or multiple lists we can merge them together using the Python addition operator. This is the simplest method but a lengthy one, let’s see an example below:
list1 = [1,2,3] list2 = ['mango','tomato','fish'] list3 =['fruit','vegetable','meat'] combined_list = list1 + list2 +list3 print(combined_list)
[1, 2, 3, 'mango', 'tomato', 'fish', 'fruit', 'vegetable', 'meat']
here we have simply added the three list into a new list named combined_list
- Use of ‘itertools’:
itertool has lots of functions for working with sequential data sets or iterable. This approach will give a better performance than ‘+’ operator approach Now let us see the same example as above using itertools
list1 = [1,2,3] list2 = ['mango','tomato','fish'] list3 =['fruit','vegetable','meat'] import itertools #importing the module combined_list1 = itertools.chain(list1 ,list2, list3) list(combined_list1)
Output : [1, 2, 3, 'mango', 'tomato', 'fish', 'fruit', 'vegetable', 'meat']
Here we are using the itertools.chain function which combined the list into the chain and provides the same output as first approaches which results inc combining or joining two or more lists.
You can use any one of the approaches to join multiple lists in Python. I and hope this would help.
Also, read: Find the most frequent value in a list in Python