Search code examples
pythonlistboolean-expressioncomparison-operators

How to check in Python for each element of a list, whether it is contained in another list?


How does it work in Python to check for each element of a list (say l1), whether it is contained in another list (say l2).

l1 = ['a', 'b', 'c']
l2 = ['b', 'c']

The desired output is [False, True, True]. So I really want a boolean vector of len(l1) and not some kind of intersection like ['b', 'c'] etc. My questions differs from this question in the sense that it is not sufficient for my problem to know whether there any element from the first list contained in the second, but which elements are, and which are not.


Solution

  • Use a list comprehension:

    [x in l2 for x in l1]
    

    Explanation:

    • I find it to be understood best, when starting with the for x in l1 part: a temporary variable x is created and looped all elements in l1 similar to a for loop.
    • for each of this x it is now checked, whether it is in l2 (so the in in x in l2 has a different meaning than the in in x in l1).