1

Any and All methods of truth value testing are really good in Python.

Basically, any returns True when atleast one of the elements is Truthy in the iterator.

all returns True only when all the elements are Truthy.

What I am not able to understand is, are those methods greedy in nature?

ie if I do

all([False, x, y, z, p, q, r])

Python should not even bother to check values of x,y,z ..et .al because the first False ensures whatever be their values, the result will always be false.

iankit
  • 8,806
  • 10
  • 50
  • 56
  • 4
    `all` short-circuits, but list creation doesn't. `[False, x, y, z, p, q, r]` will already evaluate all elements before `all` even gets called. – user2357112 Nov 20 '15 at 21:06
  • 2
    You can check this yourself: `k=iter(range(2));all(k);print next(k)`. Note that the generator does not get consumed, only all the values up to the first falsy one. – kojiro Nov 20 '15 at 21:06
  • @user2357112 interesting. so what is a good way to make something like this lazy? – iankit Nov 20 '15 at 21:08
  • @iankit use a generator. – kojiro Nov 20 '15 at 21:10
  • @iankit: You need to pass it a lazy iterable, such as a generator expression. – user2357112 Nov 20 '15 at 21:10
  • 1
    By the way: The term _lazy_ is overgeneral here. `any` and `all` use short-circuit evaluation, which is a special type of non-strict evaluation. See the [Wikipedia article on evaluation strategies](https://en.wikipedia.org/wiki/Evaluation_strategy) to get a nuanced difference. – kojiro Nov 20 '15 at 21:12

1 Answers1

0

These methods are properly lazy: They exit as soon as possible.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • The method is lazy, but the full list will be built before the method is called. You only get lazy behavior when you pass a generator. – Mark Ransom Nov 20 '15 at 21:07
  • 1
    @MarkRansom true, but that's a bit like pointing out that a list will be mutated if you use it as an initializer – it's a gotcha of the programming language, not actually reflective of the non-strictness of the operations in question. – kojiro Nov 20 '15 at 21:15