I attempted using an if statement to see if the values are the same but I'm not sure what is next?
a = [1, 2, 4, 5, 6, 7, 4, 5, 6, 7, 5, 6, 7]
b = [2, 4, 5, 6, 7, 8, 5, 4, 6, 8, 5, 6, 7, 4, 3, 5]
I attempted using an if statement to see if the values are the same but I'm not sure what is next?
a = [1, 2, 4, 5, 6, 7, 4, 5, 6, 7, 5, 6, 7]
b = [2, 4, 5, 6, 7, 8, 5, 4, 6, 8, 5, 6, 7, 4, 3, 5]
Try this: List comprehensions
# for each element (i) in each list only those not
# present in the other list will be in the new list
a_uncommon = [i for i in a if i not in b]
b_uncommon = [i for i in b if i not in a]
print('these are the uncommon elements in a', a_uncommon)
print('these are the uncommon elements in b', b_uncommon)
you could also use set
, you can refer to the operation in sets in the following link https://docs.python.org/2/library/sets.html:
list(set(a) & set(b))
# [2, 4, 5, 6, 7]
Edit In the case you also need the differnce:
a = [1, 2, 4, 5, 6, 7, 4, 5, 6, 7, 5, 6, 7]
b = [2, 4, 5, 6, 7, 8, 5, 4, 6, 8, 5, 6, 7, 4, 3, 5]
c = list(set(a) & set(b))
diff_a = list(set(a) ^ set(c))
diff_b = list(set(b) ^ set(c))
print(c) # [2, 4, 5, 6, 7]
print(diff_a) # [1]
print(diff_b) # [3, 8]
To find the common you should use the intesection, &
, of 2 sets.
To find the uncommon you should use the difference, ^
, of 2 sets.
To find items in either list but not both, you want to get the symmetric difference
a = [1, 2, 4, 5, 6, 7, 4, 5, 6, 7, 5, 6, 7]
b = [2, 4, 5, 6, 7, 8, 5, 4, 6, 8, 5, 6, 7, 4, 3, 5]
list(set(a) ^ set(b))
# [1, 3, 8]
# alternatively: set(a).symmetric_difference(b)
This will be more efficient than nested loops.
If you want the items in one that are not in the other, a simple difference will work:
set(a) - set(b)
# {1}
set(b) - set(a)
# {3, 8}