Python "all" Function With Conditional Generator Expression Returning True. Why?
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
Solution 1:
all() always returns Trueunless there is an element in the sequence that is False.
Your loop produces 0 items, so True is returned.
This is documented:
Return
Trueif 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(Truefor _ in'')
FalseSolution 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).
Post a Comment for "Python "all" Function With Conditional Generator Expression Returning True. Why?"