2

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

2
  • 1
    Just use the ternary <value> if <condition> else <value> inline syntax. Commented Jan 6, 2012 at 8:49
  • I don't understand what you're actually trying to do with 0 and logical operators that's not working as you want. Your "sample" code up at the top works fine, of course. Could you provide a sample that's not doing what you want? Commented Jan 6, 2012 at 8:58

2 Answers 2

5

Yes 0 is returning a false in your short-circuit evaluation (you can test via bool(0) which returns a false ). I think this is a lot simpler:

new = ["yes" if x else "no" for x in list]
Sign up to request clarification or add additional context in comments.

3 Comments

Yep. the a if b else c construct is the better tool for the job here.
Thanks Amber! I've updated my answer. This is much clearer. Edit: oops.
Thanks - I didn't know you could do that
1

The following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true. (See the nonzero() special method for a way to change this.)

excerpted from http://docs.python.org/reference/expressions.html#boolean-operations

1 Comment

Thanks - I've answered both my questions now :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.