if you have a list of boolean values (e.g., True
and False
) and you want to identify contiguous blocks (sequences) of True
values, here is a Python function that can help you achieve that:
def find_true_blocks(bool_list):
blocks = []
current_block = []
for index, value in enumerate(bool_list):
if value: # If the current value is True
current_block.append(index) # Append the index to the current block
else:
if current_block: # If ended a block of Trues
blocks.append(current_block) # Add the completed block to blocks
current_block = [] # Reset the current block
# Add the last block if the list ends with a True block
if current_block:
blocks.append(current_block)
return blocks
# Example usage
bool_list = [False, True, True, False, True, True, True, False, False, True]
true_blocks = find_true_blocks(bool_list)
print(true_blocks) # Output will be something like: [[1, 2], [4, 5, 6], [9]]
This code will return a list of lists, each containing the indices of contiguous True
blocks within the input list. You can modify the function to return the start and end indices of each block if that's more useful for your application.
Here is a live example: