Sometimes, we come across a problem in which we have a lot of data in a list in the form of True and False value, this kind of problem is common in Machine learning domain and sometimes we need to know that at a particular position which boolean value was present. Let’s discuss certain ways in which this can be done.
Method #1 : Using
enumerate() + zip() + list comprehension
By using combination of above three functions, this task can easily be accomplished. The enumerate function handles the role of iteration, zip function groups the like values and the logic part is handled by list comprehension.
The original list is : [True, True, False, False, True, True, True, True, False, True]
The boolean range list is : [0, 2, 4, 8, 9, 10]
Method #2 : Using
sum() + accumulate() + groupby()
The above three functions can also be clubbed together to achieve the particular task, as they use the iterators to achieve it. The sum function counts each value, groupby groups each one and all together are accumulated by the accumulate function.
The original list is : [True, True, False, False, False, True, True, True, False, False]
The boolean range list is : [0, 2, 5, 8, 10]
- Python | Check if Non-None values are contiguous
- Python Program for Largest Sum Contiguous Subarray
- Python program to find number of m contiguous elements of a List with a given sum
- Python | Boolean List AND and OR operations
- Python | Boolean list initialization
- Python | Ways to concatenate boolean to string
- Python - False indices in a boolean list
- Python | Ways to convert Boolean values to integer
- Python | Print unique rows in a given boolean matrix using Set with tuples
- Python program to fetch the indices of true values in a Boolean list
- Python | Filter list by Boolean list
- Python | range() method
- range() to a list in Python
- range() vs xrange() in Python
- Python range() function
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.