Home > Mobile >  Evaluating True and False in a python list comprehension
Evaluating True and False in a python list comprehension

Time:12-08

answers = [True, False, True, False]
formatted_answer = ["yes" if True else "no" for answer in answers]
print(formatted_answer)
['yes', 'yes', 'yes', 'yes']

Why does this statement seem to evaluate False as True but if I reword it:

formatted_answer = ["yes" if answer else "no" for answer in answers]

I get the correct result?

CodePudding user response:

formatted_answer = ["yes" if True else "no" for answer in answers]

Here, you are not comparing items in list instead just comparing the value True with if. That's why it's always returning 'yes'.

And

formatted_answer = ["yes" if answer else "no" for answer in answers]

here, you are comparing every item in the list with if. answer represent item one by one in list!

CodePudding user response:

Python evaluates expressions in the list comprehension. The condition is then tested for "truthiness" by taking its boolean value. To highlight, we could add parenthesis to highlight each.

[("yes") if bool(True) else ("no") for answer in iter(answers)]

True is an expression that is always True.

In the second case,

[("yes") if bool(answer) else ("no") for answer in iter(answers)]

Now you'll get "yes" or "no" depending on whether answer holds a truthy value.

CodePudding user response:

True is always true. Therefore the condition in your list comprehension can only ever add 'yes' to your list.

When True and False are used in an arithmetic context they evaluate to 1 and 0 respectively. This fact leads to an amusing list comprehension for your data:

answers = [True, False, True, False]
formatted_answer = [['no', 'yes'][e] for e in answers]
print(formatted_answer)

Output:

['yes', 'no', 'yes', 'no']

CodePudding user response:

I didn't get your question what are you trying to ask. But in this formatted_answer = ["yes" if True else "no" for answer in answers] if condition is always True it is not evaluating answer you provided it a True boolean value.

than in later case it is evaluating answer "if answer"

I hope you were asking same.

  • Related