0

Just something weird I noticed about the behavior of the all function, hoping to get a proper explanation of the logic or inner-workings.

Assume I have an empty list - items = [] Normally it would be "falsey", i.e bool(items) or bool([]) would be False. However, all treats it as True:

all([item for item in items]) # True
all(item for item in items) # True
all(items) # True
all([]) # True

But strangely, having an empty list inside the list, evaluates to false:

all([[]]) # False

This doesn't seem to affect the behavior of any:

any([item for item in items]) # False
any(item for item in items) # False
any(items) # False
any([]) # False
any([[]]) # False

I've tested it in python 3.7.5, I don't know if this is the behavior in other versions. Can someone please explain this?

Ofer Sadan
  • 11,391
  • 5
  • 38
  • 62
  • Not really sure what the relevance of `bool([])` would be to `any([])` and `all([])` since those functions evaluate the `bool` of the items *in* the iterable, not of the iterable itself. So of course, since `bool([])` is `False`, `all([[]])` will be `False`, since the only value in the container is falsey. For the degenerate cases (empty iterable) look at the duplicate for explanations of this behavior. – juanpa.arrivillaga Oct 30 '19 at 19:12
  • 1
    @juanpa.arrivillaga thank you for locating this duplicate, I tried searching before I asked but didn't find this result – Ofer Sadan Oct 30 '19 at 19:13
  • 1
    No problem, sometimes it isn't obvious how to construct a search query to try to find the duplicate. – juanpa.arrivillaga Oct 30 '19 at 19:14

0 Answers0