23

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.

Georgy
  • 12,464
  • 7
  • 65
  • 73
ShakeyGames
  • 277
  • 1
  • 3
  • 11
  • Does this answer your question? [How to find list intersection?](https://stackoverflow.com/questions/3697432/how-to-find-list-intersection) – Mike Elahi May 31 '20 at 11:52

4 Answers4

36

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.")
rdas
  • 20,604
  • 6
  • 33
  • 46
11

You could use a set. isdisjoint is a method which returns True if two sets have nothing in common and False if the sets overlap. After converting list1 and list2 into sets, they both contain 'item3' so isdisjoint returns False.

set(list1).isdisjoint(set(list2))
>>> list1 = ['item1','item2','item3']
>>> list2 = ['item4','item5','item3']
>>> set(list1).isdisjoint(set(list2))
False

You can combine this with the not operator to do what you want.

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

if not set(list1).isdisjoint(set(list2)):
    print("Duplicates found.")
else:
    print("No duplicates found.")
Teymour
  • 1,832
  • 1
  • 13
  • 34
0

Try using sets:

Following https://stackoverflow.com/a/2541823/1021819,

i=set.intersection(set(list1),set(list2))
if len(i) > 0:
    print('duplicates found')
else:
    print('no duplicates found')
jtlz2
  • 7,700
  • 9
  • 64
  • 114
0
list1.extend(list2)
if len(set(list1)) != len(list1) + len(list2):
    print("Duplicates Found")
else:
    print("Duplicates Not Found")

Time Analysis

>>>def fun():
       list1 = [1,2,3,4]
       list2 = [3,4,2,1]
       if len(set(list1.extend(list2)) != len(list1) + len(list2):
           return "Duplicates Found"
       else:
           return "Duplicates Not Found"
>>>%timeit fun()
>>>3.59 µs ± 213 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
>>>def fun1():
       list1 = [1,2,3,4]
       list2 = [3,4,2,1]

       if any(x in list1 for x in list2):
           return "Duplicates Found"
       else:
           return "Duplicates Not Found"
>>>%%timeit fun1():
>>>3.93 µs ± 696 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Conclusion

Both methods take nearly equal time but 'set + extend' method take slight less time to execute.