In this tutorial, we will see how to combine twolist in python
There are multiple ways to combine list in python.
Table of Contents
Using + operator
You can use + operator
to combine list in python.
Let’s understand with the help of example.
1 2 3 4 5 6 |
list1=[1,2,3,4] list2=[5,6,7,8] combinedList = list1 + list2 print("Combined List:",combinedList) |
Output:
As you can see combined list has joined list1 and list2
Using itertools.chain
Let’s understand with the help of example.
1 2 3 4 5 6 7 |
import itertools list1=[10,20,30,40] list2=[50,60,70,80] for i in itertools.chain(list1,list2): print(i) |
Output:
20
30
40
50
60
70
80
There are two advantages of using this approach.
- You don’t have to create copy of list to iterate over elements
- You can combine other iterables such as set and tuple as well
Using Additional Unpacking Generalizations
There is another way to combine two lists in python>=3.5 version.Additional Unpacking Generalizations reduces synthetic sugar with * operator but it may not be very easy to understand. This approach is bit faster than other two.
1 2 3 4 5 6 |
list1=[10,20,30,40] list2=[50,60,70,80] combinedList=[*list1,*list2] print("Combind list:",combinedList) |
Output:
Remove duplicates in combined list
In case you want to remove duplicates in combined list, you can use + operator and then convert it to set and back to list.
1 2 3 4 5 6 |
list1=[10,20,30,40] list2=[50,10,20,60] combinedList=list(set(list1 + list2)) print("Combind list without duplicates:",combinedList) |
Output:
That’s all about how to combine two lists in python