Python | Segregate True and False value indices

Python | Segregate True and False value indices

In this tutorial, we'll learn how to segregate indices of elements based on their boolean value from a list of boolean values.

Problem Statement:

Given a list containing boolean values (True and False), segregate the indices based on their respective boolean values.

Example:

For the list:

lst = [True, False, True, False, True] 

The output will be:

true_indices = [0, 2, 4] false_indices = [1, 3] 

Tutorial:

1. Using For Loop:

Iterate through the list and collect indices based on their respective values.

def segregate_boolean_indices(lst): true_indices = [] false_indices = [] for idx, value in enumerate(lst): if value: true_indices.append(idx) else: false_indices.append(idx) return true_indices, false_indices # Example usage: lst = [True, False, True, False, True] true_indices, false_indices = segregate_boolean_indices(lst) print(true_indices) # Output: [0, 2, 4] print(false_indices) # Output: [1, 3] 

2. Using List Comprehension:

This method provides a more concise way to segregate indices using list comprehension.

def segregate_boolean_indices(lst): true_indices = [idx for idx, value in enumerate(lst) if value] false_indices = [idx for idx, value in enumerate(lst) if not value] return true_indices, false_indices # Example usage: true_indices, false_indices = segregate_boolean_indices(lst) print(true_indices) # Output: [0, 2, 4] print(false_indices) # Output: [1, 3] 

Explanation:

  • The enumerate() function is used to iterate over elements of the list along with their index.

  • For each index and value pair in the list:

    1. If the value is True, the index is appended to the true_indices list.
    2. If the value is False, the index is appended to the false_indices list.

Conclusion:

Segregating indices of boolean values in a list is a straightforward task in Python. The traditional for loop approach offers a clear mechanism to collect the indices. At the same time, the list comprehension method provides a Pythonic and concise solution. Depending on the specific requirements and personal preference, either method can be used.


More Tags

ansible-template load-data-infile chai doctrine-orm npm convenience-methods token capitalization android-instant-apps pool

More Programming Guides

Other Guides

More Programming Examples