e = ''
all(e), any(e)
I expected both all(e), any(e)
returns False. But, all(e)
returns True and any(e) returns False.
I couldn't understand How is empty string both True and False?
e = ''
all(e), any(e)
I expected both all(e), any(e)
returns False. But, all(e)
returns True and any(e) returns False.
I couldn't understand How is empty string both True and False?
From the Python documentation:
all(iterable)
Return
True
if all elements of the iterable are true (or if the iterable is empty). Equivalent to:def all(iterable): for element in iterable: if not element: return False return True
When you call all()
with a string it iterates over the string as if it were a list of characters. For instance, all('foo')
is equivalent to all(['f', 'o', 'o'])
.
An empty string is like an empty list, so the bolded part above applies. Empty lists are vacuously true:
In mathematics and logic, a vacuous truth is a conditional or universal statement that is only true because the antecedent cannot be satisfied. For example, the statement "all cell phones in the room are turned off" will be true even if there are no cell phones in the room. In this case, the statement "all cell phones in the room are turned on" would also be vacuously true, as would the conjunction of the two: "all cell phones in the room are turned on and turned off". For that reason, it is sometimes said that a statement is vacuously true only because it does not really say anything.
For more examples of vacuously true statements see this excellent answer.
From the documentation on all
:
Return
True
if all elements of the iterable are true (or if the iterable is empty).
From the documentation on any
:
If the iterable is empty, return
False
.
You passed an empty iterable, so that's what happens.