differentiate lists by set

Given 2 lists:

  • list_1 = ['a', 'b', 'c', 'd', 5, 6, 7]
  • list_2 = ['a', 's', 'd', 'f', 5, 7, 9]

I want to know these answers:

  • The members that exist in both lists.
  • The members that only exist in list_1.
  • The members that only exist in list_2.

So, How to do something like that in python?

If you just learning something in python about list and loop, you may try get each member from list_1 and check that it is in the list_2 or not.

However, there is a very easier method. If you ever learn about "Set" in your mathematics course, you should know about "intersection".

You can convert a list to a set so easily by casting it to set:

  • set_1 = set(list_1)
  • set_2 = set(list_2)

Then just do the "set way":

  • Intersection means members that exist in both sets. So the answer for the first question is
    • in> set_1.intersection(set_2)
    • out> set(['a', 'd', 5, 7])
  • Well, we want the list back not the set, so cast it back to list
    • in> list(set_1.intersection(set_2))
    • out> ['a', 'd', 5, 7]
  • So what are the members that only exist on list_1 or list_2? You can do the operation "minus" (-) like this:
    • in> list(set_1 - set_2)
    • out> ['c', 'b', 6]
    • in> list(set_2 - set_1)
    • out> [9, 's', 'f']

Done...

Post your comment:

Author:

  • chaiwat

Archives:

Powered by Django.