Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the indexes of truthy elements of a boolean list as a list/tuple

Tags:

python

json

list

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.

like image 419
MLister Avatar asked Oct 25 '12 20:10

MLister


1 Answers

[i for i, elem in enumerate(bool_list, 1) if elem]
like image 60
Lev Levitsky Avatar answered Sep 30 '22 19:09

Lev Levitsky