The reason you get generator objects back is because you use ()
, hence those make generator expressions, which are not evaluated until you iterate through them.
What you really should be using if simple in
operator. Example -
>>> A = ['a', 'b', 'c', 'e']
>>> B = ['a', 'b', 'c', 'd', 'e', 'f']
>>> res = [1 if x in A else 0 for x in B]
>>> res
[1, 1, 1, 0, 1, 0]
If your usecase is more complex and you have to use is
operator to compare elements of A
and B
. Then you can use any()
function to iterate through the generator expression and return True
if a match is found, other False
. Example -
res = [1 if any(a is b for a in A) else 0 for b in B]
Demo -
>>> A = ['a', 'b', 'c', 'e']
>>> B = ['a', 'b', 'c', 'd', 'e', 'f']
>>> res = [1 if any(a is b for a in A) else 0 for b in B]
>>> res
[1, 1, 1, 0, 1, 0]
Also, according to your question -
I would like boolean list of that specifies whether an element of A is equal to an element of B.
If what you really want is a boolean (rather than 1
or 0
) , then you can simply change above examples to -
Example 1 -
res = [x in A for x in B]
Example 2 -
res = [any(a is b for a in A) for b in B]