Why does [] and bool return []?

时间:2018-10-02 09:17:02

标签: python python-2.7

I am trying to return a boolean in a function like this:

return mylist and any(condition(x) for x in mylist)

The behavior should be to return True if the list is empty or if any element in it meets the condition. I am using the first operand as a shortcircuit since any would return True if the list was empty, which is not what I am after.

I would expect [] and boolval to return False since the list is empty, but to my surprise it returns [] whether boolval is True or False. I would expect the first operand to be automatically evaluated as a boolean since it is involved in a comparison operation, and not whatever is happening.

I am not really asking how to solve my problem, which is easily done by an explicit type conversion: bool(mylist), but rather asking what is happening and why.

edit: when I ask "why" this is happening I am not looking for the "facts" only, as they are already explained in the linked duplicate question, but also the reasons behind the implementation of this behavior.

3 个答案:

答案 0 :(得分:5)

par(mfrow = c(4, 4)) for (i in c(6:17)) { print(ggpubr::ggboxplot(logdat, x = "Diagnostic", y = names(logdat)[i] , color = "Diagnostic", add = "jitter") + stat_compare_means(comparisons = my_comparisons, method = "t.test")) } and运算符 返回or。他们返回最后评估的结果(其他动态语言也是如此,例如javascript)。

official documentation describes that

  • 对于True/False,第一个伪造的值或最后一个操作数
  • 用于and,第一个真实值或最后一个操作数

这是设计使然,因此您可以创建类似or的表达式。因此,如果要保证返回布尔值,则必须

return username or 'guest'

代替

return bool(x or y)

答案 1 :(得分:1)

因为凯尔伍德说过:

  

x and y如果x为假,则给出x,否则给出y

这就是重点({and不是or :-)),所以最好的是:

return all([my_list,any(condition(x) for x in my_list)])

答案 2 :(得分:0)

这与python如何评估表达式有关。

一个空列表被python认为是假的,这意味着'and'之后的代码将不会执行,因为这不会改变结果。

Python无需将空列表转换为bool,因为它不会与任何内容进行比较,而只是将其作为空列表返回。

这应该不会为您带来任何改变,如果您测试该函数的返回值,则将以与该函数返回False相同的方式求值。