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.
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
As the documentation states, what all
does is:
Return True if all elements of the iterable are true (or if the iterable is empty).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With