Unexpected Outcome with Generator Expressions and Any/All

Viewed 44

I'm having an odd issue with evaluating a generator expression.

My code has a generator expression that tests a few conditions. Let's call it "gen_ex". If I turn it into a list to see the output:

print(list(gen_ex))

I get this:

[False, False, False, False, True, True, False, False, False]

However, when I use any() and all() on it, I get unexpected results.

any(gen_ex)

return False, while:

all(gen_ex)

returns True.

Should this be the expected behavior? Or is something weird happening behind the scenes?

1 Answers

Generators cannot iterated over multiple times. The first call to list consumes all the values.

>>> gen_ex = (x for x in (1,2,3))
>>> list(gen_ex)
[1,2,3]
>>> list(gen_ex)
[]

As such, both any and all are seeing an empty sequence of values as well. The return values you see are the base cases:

  • any([]) is False because there is no True element in the list (i.e., it is not true that an element in the argument evaluates to True)
  • all([]) is True because there are no False elements in the list (i.e., it is true that every element in the list is True, because there are no elements)
Related