Search code examples
python-3.xlistbooleananyshort-circuiting

Is there a way to pull the index of a Python list of booleans of where short circuiting occurs?


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


Solution

  • 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.