My main focus has been on any
and all
function of Python 3.7. Sometimes, I would like to figure out where the short-circuit occurs in a list of booleans
i.e.
any([False, False, True, False, True, True])
would return 2.
What is a way to do so without using a loop?
Edit: I realized that this is a first occurrence problem. Which, already has many solutions out there :p
You can use itertools.takewhile
, which accepts a function and an iterable. Each element of the iterable is passed into the function and taken until the first False
.
>>> from itertools import takewhile
>>> lst = [False, False, True, False, True, True]
>>> len(list(takewhile(lambda x: not x, lst)))
2
Another option from the comments is
next(i for i, val in enumerate(mylist) if val)
which makes an iterator of indices of truthy values in mylist
and forwards it one step to the first truthy value index, which is also short-circuiting and space-efficient.
any
does short circuit although it doesn't produce an index.