Python – Extract Row with any Boolean True

When working with nested lists or tuples containing Boolean values, you may need to extract only those rows that contain at least one True value. Python's any() function combined with list comprehension provides an elegant solution for this task.

Syntax

result = [row for row in data if any(row)]

Example

Here's how to extract rows containing at least one Boolean True ?

my_data = [[False, True], [False, False], [True, False, True], [False]]

print("The original data is:")
print(my_data)

my_result = [row for row in my_data if any(element for element in row)]

print("Rows with at least one True:")
print(my_result)
The original data is:
[[False, True], [False, False], [True, False, True], [False]]
Rows with at least one True:
[[False, True], [True, False, True]]

How It Works

The solution uses two key components:

  • List comprehension − Iterates through each row in the data structure

  • any() function − Returns True if at least one element in the row is True, otherwise False

  • Generator expression(element for element in row) creates an iterator over row elements

Simplified Version

Since any() can work directly with iterables, you can simplify the code ?

my_data = [[False, True], [False, False], [True, False, True], [False]]

# Simplified version - any() works directly on the row
my_result = [row for row in my_data if any(row)]

print("Simplified result:")
print(my_result)
Simplified result:
[[False, True], [True, False, True]]

Practical Example

Here's a real-world example with task completion status ?

# Task completion status: [Task1, Task2, Task3]
projects = [
    [True, False, False],   # Project A: 1 task done
    [False, False, False],  # Project B: no tasks done  
    [True, True, False],    # Project C: 2 tasks done
    [False, False, False]   # Project D: no tasks done
]

# Extract projects with at least one completed task
active_projects = [project for project in projects if any(project)]

print("Projects with completed tasks:")
for i, project in enumerate(active_projects):
    print(f"Project {chr(65 + projects.index(project))}: {project}")
Projects with completed tasks:
Project A: [True, False, False]
Project C: [True, True, False]

Conclusion

Use any() with list comprehension to efficiently filter rows containing at least one True value. The any() function works directly on iterables, making the code clean and readable.

Updated on: 2026-03-26T01:04:04+05:30

258 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements