What is the easiest way to compare the elements of two lists say A and B with one another, and add the elements which are present in B to A only if they are not present in A?
To illustrate, Take list A = {1,2,3} list B = {3,4,5}
So after the operation AUB I want list A = {1,2,3,4,5}
Union of two lists means combining two lists into one, all the elements from list A and list B, and putting them inside a single new list.
To perform the union of two lists in python, we just have to create an output list that should contain elements from both the input lists. For instance, if we have list1=[1,2,3,4,5,6] and list2=[2,4,6,8,10,12] , the union of list1 and list2 will be [1,2,3,4,5,6,8,10,12] .
The easiest way is to use LINQ's Union
method:
var aUb = A.Union(B).ToList();
If it is a list, you can also use AddRange method.
var listB = new List<int>{3, 4, 5}; var listA = new List<int>{1, 2, 3, 4, 5}; listA.AddRange(listB); // listA now has elements of listB also.
If you need new list (and exclude the duplicate), you can use Union
var listB = new List<int>{3, 4, 5}; var listA = new List<int>{1, 2, 3, 4, 5}; var listFinal = listA.Union(listB);
If you need new list (and include the duplicate), you can use Concat
var listB = new List<int>{3, 4, 5}; var listA = new List<int>{1, 2, 3, 4, 5}; var listFinal = listA.Concat(listB);
If you need common items, you can use Intersect.
var listB = new List<int>{3, 4, 5}; var listA = new List<int>{1, 2, 3, 4}; var listFinal = listA.Intersect(listB); //3,4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With