-1
list1 = ["aaa", "bba", "bb"]
list2 = ["aav", "bb", "ace"]
list3 = (the elements in list1 and list2) 
list4 = (the elements in list1 but not in list2)

So, I have 2 lists here and I want to check the elements that are in both lists and the elements that exist in list1 and not in list2

3 Answers3

3

use list comprehension.

list3 = [item for item in list1 if item in list2]
list4 = [item for item in list1 if item not in list2]
sudonym
  • 3,788
  • 4
  • 36
  • 61
3

Try using sets. Like this:

list1 = ["aaa", "bba", "bb"]
list2 = ["aav", "bb", "ace"]
list3 = list(set(list1) & set(list2))
list4 = list(set(list1) - set(list2))
print(list3)
print(list4)

Or same as above, but using set functions:

list1 = ["aaa", "bba", "bb"]
list2 = ["aav", "bb", "ace"]
list3 = list(set(list1).intersection(set(list2))) # same as &
list4 = list(set(list1).difference(set(list2))) # same as -
print(list3)
print(list4)
ppwater
  • 2,315
  • 4
  • 15
  • 29
1
In [8]: list1 = ["aaa", "bba", "bb"]
   ...: list2 = ["aav", "bb", "ace"]

In [9]: set(list1) & set(list2)
Out[9]: {'bb'}

In [10]: set(list1) - set(list2)
Out[10]: {'aaa', 'bba'}
idar
  • 614
  • 6
  • 13