Python Forum

Full Version: Create a List for Boolean Mask.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all,

I am trying to find a better way to create a Boolean Mask based on certain conditions. Here is the question and my way to answer it.

Question:
l = ["a","b","a","c"], "a" is a qualified data for the future use. Create a list with boolean values.

l = ["a","b","a","c"]
L = []
for i in l:
	if i == "a":
		L.append(True)
	else:
		L.append(False)
Result:
L = [True,False,True,False]

Thanks!
You don't need the conditional. Just append i == 'a'.
(Oct-08-2018, 09:59 PM)ichabod801 Wrote: [ -> ]You don't need the conditional. Just append i == 'a'.

Hi ichabod801, thanks for the solution.

Base on your reply, I tried a further simplification,

l = ["a","b","a","c"]
L = [x for x == 'a' in l]
python told me "invalid syntax"

Could you tell me the reason for this failure?
You want
[x == 'a' for x in l]
(Oct-09-2018, 12:03 AM)micseydel Wrote: [ -> ]You want
[x == 'a' for x in l]

Wow,it's like magic. Thanks!