-2

I think all will skip the rest of an array of boolean values as soon as it encounters a False. Can anyone please confirm the same?

array = [False, True, True ...(1000s of values of True)]

all(array)

The time complexity to run the above set of statements would/should be constant, i.e. O(1), right?

martineau
  • 119,623
  • 25
  • 170
  • 301
Aparna Chaganti
  • 599
  • 2
  • 5
  • 15
  • It will skip the rest of the list. `any` and `all` are evaluated _lazily_. But _creating_ the list is still O(n). – jonrsharpe Jan 02 '22 at 19:54
  • 1
    "Can anyone please confirm the same?" The way to do this is to *read the documentation*. "The time complexity to run the above set of statements would/should be constant, i.e. O(1), right?" No, because you have to *create the list* before you can use `all`. – Karl Knechtel Jan 02 '22 at 19:58

1 Answers1

3

all will stop. Since it works with any arbitrary iterable, you can see this using a list iterator.

>>> i = iter([False, True, True])
>>> all(i)
False
>>> list(i)
[True, True]

If all hadn't stopped, list(i) would have returned the empty list.

Another way to see this is to see that all will terminate when given an infinite sequence.

>>> from itertools import repeat
>>> all(repeat(False))
False

all(repeat(True)), on the other hand, will never terminate.

chepner
  • 497,756
  • 71
  • 530
  • 681