- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Python - Contiguous Boolean Range

Given a list of values, we are interested to know at which position are the Boolean values present as a contiguous list. Which means after we encounter a value which is TRUE there is a continuous value of true from that position until FALSE value is found. Similarly when a FALSE is found there is a contiguous value of FALSE until TRUE is found.

## With itertools

W can use accumulate along with groupby from the itertools module. In this example we take a given list and then apply the accumulate function to keep track of the values that are brought together using the sum function.The last value in the list is the last position where the given list ends.

## Example

from itertools import accumulate, groupby # Given list listA = [False, True,True,False,False] print("Given list : \n",listA) # Applying accumulate res = [0] + list(accumulate(sum(1 for x in y) for x, y in groupby(listA))) # Result print("Positions for Range of contigous values:\n ",res)

## Output

Running the above code gives us the following result −

Given list : [False, True, True, False, False] Positions for Range of contigous values: [0, 1, 3, 5]

## Using enumerate

The enumerate function along with zip function is used to list the position by comparing each element with the next one. If they are not equal then a new position value is consideredas the staring point of the contiguous range.

## Example

# Given list listA = [False, True,True,False,False] print("Given list : \n",listA) # Applying enumerate res = [e for e, (x, y) in enumerate(zip([2]+ listA, listA + [2])) if x != y] # Result print("Positions for Range of contigous values:\n ",res)

## Output

Running the above code gives us the following result −

Given list : [False, True, True, False, False] Positions for Range of contigous values: [0, 1, 3, 5]

- Related Questions & Answers
- Return a boolean indicating whether the data is contiguous in Numpy
- Python - Group contiguous strings in List
- Python Boolean Operations
- Difference Between Contiguous and Non-contiguous Memory Allocation
- Largest product of contiguous digits in Python
- Boolean Indexing in Python
- Boolean Values in Python
- Boolean list initialization in Python
- Largest Sum Contiguous Subarray
- Contiguous Array in C++
- What are boolean operators in Python?
- Parsing A Boolean Expression in Python
- Program to find maximum product of contiguous subarray in Python
- Program to find contiguous intervals of a unique array in Python
- Program to find length of contiguous strictly increasing sublist in Python