Python “all” function with conditional generator expression returning True. Why?

一笑奈何 提交于 2019-12-18 08:43:11

问题


Can anyone help me understand why the following Python script returns True?

x = ''
y = all(i == ' ' for i in x)
print(y)

I imagine it's something to do with x being a zero-length entity, but cannot fully comprehend.


回答1:


all() always returns True unless there is an element in the sequence that is False.

Your loop produces 0 items, so True is returned.

This is documented:

Return True if all elements of the iterable are true (or if the iterable is empty).

Emphasis mine.

Similarly, any() will always return False, unless an element in the sequence is True, so for empty sequences, any() returns the default:

>>> any(True for _ in '')
False



回答2:


As the documentation states, what all does is:

Return True if all elements of the iterable are true (or if the iterable is empty).



来源:https://stackoverflow.com/questions/19257821/python-all-function-with-conditional-generator-expression-returning-true-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!