Search code examples
pythonlistcontains

Check if at least 2 values from a list are in another list


I have a list a:

["a", "b", "c", "d"]

and list b1:

["a", "b", "x"]

and b2:

["a", "z", "x"]

If b1 has at least 2 elements from a the result is True. If b2 has at least 2 elements from a the result is True.

In this example b1 == True and b2 == False.

How can I check that in Python?


Solution

  • This function should do what you want, using sets and set intersection.

    def f(a, b):
        return len(set(a) & set(b)) >= 2
    

    Usage:

    >>> f(a, b1)
    True
    >>> f(a, b2)
    False
    

    Alternatively, if b has repeated elements, you could use:

    def f2(a, b):
        return sum(x in a for x in b) >= 2
    

    Test:

    >>> f(a, ['a', 'a', 'x'])
    False
    >>> f2(a, ['a', 'a', 'x'])
    True