Python Forum
Create a List for Boolean Mask. - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Create a List for Boolean Mask. (/thread-13290.html)



Create a List for Boolean Mask. - leoahum - Oct-08-2018

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!


RE: Create a List for Boolean Mask. - ichabod801 - Oct-08-2018

You don't need the conditional. Just append i == 'a'.


RE: Create a List for Boolean Mask. - leoahum - Oct-08-2018

(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?


RE: Create a List for Boolean Mask. - micseydel - Oct-09-2018

You want
[x == 'a' for x in l]



RE: Create a List for Boolean Mask. - leoahum - Oct-09-2018

(Oct-09-2018, 12:03 AM)micseydel Wrote: You want
[x == 'a' for x in l]

Wow,it's like magic. Thanks!