Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I check if a list contains any item from another list? [duplicate]

using Python, I want to check if a list contains an item/value that is also present in another list. For example, here is what I am trying to do:

list1 = ['item1','item2','item3']
list2 = ['item4','item5','item3']

if list1 contains any items also in list2:
    print("Duplicates found.")
else:
    print("No duplicates found.")

As you can see, list2 contains an item that is also found in list1, which is 'item3'. Is there any way I can detect if this occurs?

Thanks.

like image 469
ShakeyGames Avatar asked Sep 06 '25 22:09

ShakeyGames


1 Answers

Using any() along with a generator expression:

list1 = ['item1','item2','item3']
list2 = ['item4','item5','item3']

if any(x in list1 for x in list2):
    print("Duplicates found.")
else:
    print("No duplicates found.")
like image 110
rdas Avatar answered Sep 10 '25 02:09

rdas