Skip to content Skip to sidebar Skip to footer

Compare Two List, And Create Other Two Lists With Intersection And Difference

I have 2 lists A and B. In the B list I can have multiple elements from list A. For example: A = [1,3,5,7, 9, 12, 14] B = [1,2,3,3,7,9,7,3,14,14,1,3,2,5,5] I want to create: to

Solution 1:

#to create a list with ids that are in A and found in B (unique)
resultlist=list(set(A)&set(B))
print(list(set(A)&set(B)))


#to create a list of ids that are in A and have no corresponding in B (unique)print(list(set(A)-set(B)))


#the numbers in B, that don't have a corespondent in Aprint(list(set(B)-set(A)))

Solution 2:

Convert the list to set and then perform set operations

>>>set_A = set(A)>>>set_B = set(B)>>>list(set_A & set_B)
[1, 3, 5, 7, 9, 14]         # set intersection

>>>list(set_A - set_B)     # set difference
[12]

>>>list(set_B - set_A)
[2]

Solution 3:

With python you can simply use the set type:

list(set(A) & set(B))

will return a list containing the element intersection between lists A and B.

list(set(A) - set(B))

Will return a list containing all the elements that are in A and not in B.

Vice versa:

list(set(B) - set(A))

Will return a list containing all the elements that are in B and not in A.

Solution 4:

you could use the 'a in L' functionality, which will return True if an element is in a List. e.g.

A = [1,3,5,7, 9, 12, 14]
B = [1,2,3,3,7,9,7,3,14,14,1,3,2,5,5]

common = []
uncommon = []

for a in A:
    if a in B:
      common.append(a)
    else:
      uncommon.append(a)
print(common)
print(uncommon)

this should give you a good hint on how to approach the other question. best

Solution 5:

Use set operations:

A = [1, 3, 5, 7, 9, 12, 14]
B = [1, 2, 3, 3, 7, 9, 7, 3, 14, 14, 1, 3, 2, 5, 5]

sa = set(A)
sb = set(B)

# intersectionl1 = list(sa & sb)
# [1, 2, 3, 5, 7, 9, 12, 14]# differencesl2 = list(sa - sb)
# [12]l3 = list(sb - sa)
# [2]

Post a Comment for "Compare Two List, And Create Other Two Lists With Intersection And Difference"