Given a boolean list such as [True, False, False, True, False, True]
, what is the quickest way to get a list/tuple containing the indexes (starting from 1, not zero-indexed) of the Truthy elements in the original list? So for the list above, it should returns [1, 4, 6]
or (1, 4, 6)
.
I was using a generator like this:
def get_truthy_ones(self, bool_list):
return (idx + 1 for idx, value in enumerate(bool_list) if value)
However, this creates a problem when I want to encode the results in a JSON
object, as JSON
does not encode generators.
[i for i, elem in enumerate(bool_list, 1) if elem]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With