0
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?

Mine
  • 11
  • 3
  • 5
    `e` is an empty iterable so the behavior is the same as `all([])` and `any([])`. In an iterable of zero elements, it's true that all of the elements are truthy (`all` means every element must be true, that's trivially true when we have nothing in the iterable). In an iterable of zero elements, it's false that all zero of the elements are truthy (`any` means at least one must be true, but because there's nothing in the iterable, it's trivially false). – ggorlen Feb 13 '21 at 03:54

2 Answers2

1

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.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • Really Thank you so much!!!! Because of your explaination, I understand 100% this curiosity!!!! especially, I think it is very good description that statement "all cell phones in the room are turned off" will be true even if there are no cell phones in the room. Very Thank you!!!! – Mine Feb 14 '21 at 03:55
  • The vacouos truth's reference is gold, loving it. – aran Feb 19 '21 at 02:21
0

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.

TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97