Python is a programming language that has a number of functionality. One of the features is the capacity to combine two separate lists into one, which is called the union of two lists. In this entire tutorial, you will know how to find the Union of two lists in Python in various ways.
Methods to Find Union of Two Lists in Python
Python offers many techniques to merge two lists. You will know all these techniques in this section.
Method 1: Plus sign (+) operator
This operator joins together two different lists into one. For instance, if you have two lists named list1 and list2, you may unite them into one with the help of the following pieces of code:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
print(list1 + list2)
Output
[1, 2, 3, 4, 5, 6]
Method 2: Union of two lists using the extend() function
Using the extend() function, all of the elements from one list are added to the end of another. For instance, if you have two lists named list1 and list2, you may combine them into one by the following code:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
print(list1.extend(list2))
Output
[1, 2, 3, 4, 5, 6]
Method 3: Use itertools module
With the itertools module’s help, you may perform many methods on lists. The chain() process is one example. The input is the two lists, and the yield is a new list containing all the input elements. The following code makes this happen:
import itertools
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list(itertools.chain(list1, list2))
Output
[1, 2, 3, 4, 5, 6]
Method 4: Union of two lists using the collections module
With the collections module’s help, you may perform various functions on lists. The chain() function is one example. This function accepts one or more lists and returns a new list with all the entries. The following code does this:
import collections
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list(collections.chain(list1, list2))
Output
[1, 2, 3, 4, 5, 6]
Method 5: functools module
You may perform a diverse range of operations on lists with this module. The reduce() operation is one example. This function receives two lists and creates another list with all the elements. The following code carries this out:
import functools
list1 = [1, 2, 3] list2 = [4, 5, 6] print(functools.reduce(lambda x, y: x+y, list1+list2))
Output
[1, 2, 3, 4, 5, 6]
Conclusion
In this tutorial, we have learned how to find the Union of two lists in Python in various ways. I hope this tutorial was helpful to you and that you were able to understand everything that was covered. Try to implement these methods in your own code and see which one works best for you. If you have any questions then you can ask us by leaving them in the comment section.
Leave a Reply