-3

I have a list --> list_1 = ['a', 'b', 'c']

I have another list --> list_2 = ['a', 'x', 'y']

Now, I want to compare and check if each element in list_1 are there in list_2.

How do I check that?

PS: The end result of the program will be like, if the element in list_1 is in list_2, do TASK1, else do TASK 2.

Software Fan
  • 609
  • 3
  • 8
  • 17
  • Possible duplicate of [Python - Checking every item in a list against every other item efficiently](https://stackoverflow.com/questions/51661522/python-checking-every-item-in-a-list-against-every-other-item-efficiently) – Aeolus Aug 12 '18 at 13:53
  • Does the order matter? And if 'a' is in the first list twice and once in the second, is that equal? You can probably use sets and `==`. – RemcoGerlich Aug 12 '18 at 13:53
  • Also, have a look at [formatting](https://stackoverflow.com/editing-help). – palivek Aug 12 '18 at 13:54
  • `set(list_1).issubset(list_2)` gives you true or false, efficiently, provided duplicates don't matter. – Martijn Pieters Aug 12 '18 at 13:55
  • @RemcoGerlich Let us assume that no items are repeated in either lists. – Software Fan Aug 12 '18 at 13:55
  • If you need to account for duplicates, then use [`collections.Counter()`](https://docs.python.org/3/library/collections.html#collections.Counter) instead of sets and [then test for inclusion](https://stackoverflow.com/questions/29575660/test-if-python-counter-is-contained-in-another-counter). – Martijn Pieters Aug 12 '18 at 14:08

1 Answers1

0

You can use the word in to check if a element is in a list:

list1 = ["a","b","c"]
list2 = ["a","b"]

for i in list1:
    if i in list2:
        # do something
        print (i, "ok")
    else:
        # do something
        print (i, "not found")
Allexj
  • 1,375
  • 6
  • 14
  • 29