Picking up a tip from someone else on this site, I’ve been using logical operators to express conditional logic in list comprehension as a shortcut to using full for loops with if statements.
For example, if I had a list [1, 0, 0, 1, 1] that I wanted to turn into [“Yes”, “No”, “No”, “Yes”, “Yes”] I could do it like this:
original = [1, 0, 0, 1, 1]
new = [((x==1) and "Yes") or "No" for x in original]
The problem I have is that I get some very strange results when I use the logical operators with 0 in this way. The results occur regardless of whether I’m using list comprehension or not.
These:
print((True and 1.0) or "Wrong")
print((True and -1.0) or "Wrong")
print((True and "1.0") or "Wrong")
print((True and 1) or "Wrong")
Correctly (I think) output:
1.0
-1.0
1.0
1
However these:
print((True and 0) or "Wrong")
print((True and 0.0) or "Wrong")
Output:
Wrong
Wrong
I think that Python is implicitly converting both 0 and 0.0 to a boolean False, and any other value of any other type to True
Can someone confirm whether:
a. This is the case and/or
b. Is there a way to achieve what I’m after in list comprehension another way (with a lamda or something)
Many thanks
Chris
Yes
0is returning a false in your short-circuit evaluation (you can test viabool(0)which returns afalse). I think this is a lot simpler: