In this post we will see how to merge two or more lists in python – various list examples.
Method 1 -Concatenate Two or more Lists in Python
Lets take example of two list as follow –
List1 = [1,2,3,4,5]
List2 = [6,7,8,9]
Output after merging two list should be –
CombinedList = [ 1,2,3,4,5,6,7,8,9]
I python this can be done very easily by simply joining them using ‘+’ operator as –
CombineList =List1 + List 2
a,b=[1,2,3],[4,5] c=a+b c
Lets Try to Run it –
a,b=[1,2,3],[4,5]
c=a+b
c
c=a+b
Method 2 – Concatenate Two List using Extend
Lets take another route to achieve same task – Using Extend – here is example –
a = [‘it’]
b = [‘is’]
c = [‘nice’]
a.extend(b)
a.extend(c)
We should have output as –
a = [‘it’, is’, ‘nice’]
Lets try to run this program –
a = ['it']
b = ['was']
c = ['annoying']
a.extend(b)
a.extend(c)
a
a = ['it'] b = ['was'] c = ['annoying'] a.extend(b) a.extend(c)
Method 3- Use Itertools to Concatenate List
There are multiple ways to merge lists in python, in this method we will use itertools to merge the two list as follows –
import itertools list = itertools.chain(['it'], ['is'], ['nice']) list(list) list
Lets try to execute it –
import itertools
list = itertools.chain(['it'], ['is'], ['nice'])
list(list)
list
list
Bonus Method – Most Commonly Used
Lets take an live example where your lists are dynamic i.e. you dont know the number of lists and you want to merge all the list then you need to use the extend method in loop to merge all the lists.
Example :
a=[['one','two'],['three','four']] outList=[] for i in a: outList.append(i)
Try to find output of this program, take this as the exercise.