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.
Use a list comprehension:
[x in l2 for x in l1]
Explanation:
for x in l1
part: a temporary variable x
is created and looped all elements in l1
similar to a for loop.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
).