-1

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]
David
  • 8,113
  • 2
  • 17
  • 36
Santi
  • 1
  • 1
  • Please clarify your problem. What have you tried so far? – Austin Jun 15 '20 at 05:00
  • This is homework question, don't ask others to solve your homework, show us your code and your approach so far – Agent_Orange Jun 15 '20 at 05:01
  • Does this answer your question? [Python: how to find common values in three lists](https://stackoverflow.com/questions/28061223/python-how-to-find-common-values-in-three-lists) – MendelG Jun 15 '20 at 05:01

3 Answers3

0

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)
leopardxpreload
  • 767
  • 5
  • 17
0

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.

David
  • 8,113
  • 2
  • 17
  • 36
0

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}
Mark
  • 90,562
  • 7
  • 108
  • 148