[Solved] Index lists for specific repeating element


The following is a much shorter and solution, and might be preferable –

main_list = [True, True, False, False, True, True, True, True, True, False]

def my_diff(my_list):
    return [1 if my_list[0] else 0] + [y - x for x, y in zip(my_list[:-1], my_list[1:])]

solution = [i for i, x in enumerate(my_diff(main_list)) if x == 1]

print(solution)
# [0, 4]

Explanation:
I’d personally solve this by using np.diff, and simply searching for the “transitions” (from False to True). But seeing as numpy is out of scope, I’ve just implemented a simple diff function, and the beginning of a sequence of Trues is the same as having a difference of 1 between two consecutive elements.
And to make sure the first element isn’t missed, if it’s True then it’s by definition the beginning of a sequence, and so we plant a 1 in place. Otherwise we don’t :-).

To sum things up – look for “element – prev-element” being equal 1.

4

solved Index lists for specific repeating element