1

Documentation:

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

However, I can't explain results 4 and 5 below using Python3:

  1. tupleData = ((1), (1, 4), (2, 3)) return True (OK)
  2. tupleData = ((0), (1, 4), (2, 3)) returns False (OK)
  3. tupleData = ((None), (1, 4), (2, 3)) returns False (OK)
  4. tupleData = ((0, None), (1, 4), (2, 3)) returns True (Why?)
  5. tupleData = ((), (1, 4), (2, 3)) returns False (Why, isn't it supposed to return True if the iterable is empty?

Thanks everyone, especially Barmar. With the points you mentioned now I understand these outputs: any() and all() here iterate over the top-level tuple (and not the nested tuples). an empty nested tuple is considered a False element in the top-level tuple, and vice versa.

Roz
  • 195
  • 2
  • 10
  • 1
    A non-empty tuple is true. None of the tuples in 4 are empty. – Barmar Oct 20 '20 at 05:53
  • In 4, all the items in the iterable have something in them, so are all considered "truthy". In 5, the first item isn't, so every item in the iterable isn't considered that way. Python considers empty sequences `False` (regardless of the value of their sub-contents). – martineau Oct 20 '20 at 05:54
  • 1
    Does this answer your question? [How do Python's any and all functions work?](https://stackoverflow.com/questions/19389490/how-do-pythons-any-and-all-functions-work) – mulaixi Oct 20 '20 at 05:54
  • 1
    BTW, `(None)` in 3 is the same as just `None`. That's not a tuple, you need to write `(None,)` to get a tuple with one element. – Barmar Oct 20 '20 at 05:55
  • Empty iterables return `False`. Thats why result 4 returned `True`. The first `tuple` is not empty, and since all the other iterables are not empty, the result for 4 is `True`. It is the same for result 5. Since the first `tuple` is empty, then not all are `True` thus the result is `False` – בנימין כהן Oct 20 '20 at 05:56
  • The only iterable that matters is the top-level tuple. It's not iterating over the nested tuples, so `(0, None)` is true even though both its elements are false. – Barmar Oct 20 '20 at 05:57

1 Answers1

0

For the 4th case: look at this page https://note.nkmk.me/en/python-tuple-single-empty/ , to create a tuple with one element you have to explicitly add the comma to the line. So (0) is considered 0, and that’s why it’s considered false. (0, None) is a tuple, whose elements are all false, but it’s not empty. That’s why is considered True. For the 5th case: it is the iterable which you call the all method on that can be empty, otherwise every element in the iterable will be checked. In your case the first element is an empty tulle, which is a Falsey value.