Python – Extract Row with any Boolean True

PythonServer Side ProgrammingProgramming

When it is required to extract row with any Boolean True, a list comprehension is used along with the ‘any’ operator.

Below is a demonstration of the same −

Example

 Live Demo

my_tuple = [[False, True], [False, False], [True, False, True], [False]]

print("The tuple is :")
print(my_tuple)

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

print("The result is ")
print(my_result)

Output

The tuple is :
[[False, True], [False, False], [True, False, True], [False]]
The result is
[[False, True], [True, False, True]]

Explanation

  • A list of list is defined and displayed on the console.

  • A list comprehension is used to check if any element is present in the list.

  • The ‘any’ operator gives a True or False result.

  • This is converted to a list and is assigned to a variable.

  • This is the output that is displayed on the console.

raja
Updated on 06-Sep-2021 08:13:16

Advertisements