Python | Matrix True Summation

Checking a number/element by a condition is a common problem one faces and is done in almost every program. Sometimes we also require to get the totals that match the particular condition to have a distinguish which to not match for further utilization like in data Science. Let’s discuss certain ways in which we can count True values in Matrix.
Method #1 : Using sum() + generator expression
This method uses the trick of adding 1 to the sum whenever the generator expression returns true. By the time list gets exhausted, summation of count of numbers matching a condition is returned.
Step-by-step approach :
- Import the chain function from the itertools module. chain function is used to concatenate two or more iterable objects.
- Define a list called test_list that contains multiple nested lists, each with two elements. The first element is an integer, and the second element is a boolean value.
- Print the original list using the print() function and str() conversion to display the original list in a string format.
- Use the chain.from_iterable() function to create a single iterator that contains all the elements from all the nested lists in test_list. from_iterable() function is used to create an iterator from nested lists.
- Use a generator expression to generate a sequence of True values that are present in the single iterator obtained from step 4.
- Use the sum() function to sum up all the True values generated in step 5.
- Store the result obtained in step 6 in a variable called res.
- Print the number of True elements present in the given matrix by converting res to a string using the str() function and concatenating it with a string message using the + operator.
- The program ends.
Python3
# Python 3 code to demonstrate# Matrix True Summation# using sum() + generator expressionfrom itertools import chain# initializing listtest_list = [[3, True], [True, 6], [True, 9]]# printing original listprint("The original list is : " + str(test_list))# using sum() + generator expression# Matrix True Summationres = sum(1 for i in chain.from_iterable(test_list) if i == True)# printing resultprint("The number of True elements: " + str(res)) |
The original list is : [[3, True], [True, 6], [True, 9]] The number of True elements: 3
Time Complexity: O(n), where n is the length of list.
Auxiliary Space: O(1)
Method #2 : Using sum() + map()
map() does the task almost similar to the generator expression, difference is just the internal data structure employed by it is different hence more efficient.
Step by step approach :
- We start by importing the itertools module which provides a chain() function to concatenate multiple iterables into one iterable.
- We then initialize a 2D list (list of lists) called test_list with some values. Each sublist represents a row in a matrix.
- We print the original list using the print() function and concatenation operator + to join the string and list.
- We use the map() function to create a new iterable that contains 1s for every occurrence of True in test_list, and 0s otherwise. The lambda function lambda i: i == True returns True if the input argument is True and False otherwise.
- We use chain.from_iterable() function to convert the 2D list into a 1D list (i.e., chain all sublists into one list). This is because the map() function works on a single iterable, not a nested iterable.
- We pass the mapped iterable to the sum() function which adds up all the values in the iterable and returns the sum.
- Finally, we print the result using the print() function and concatenation operator + to join the string and integer.
Python3
# Python 3 code to demonstrate# Matrix True Summation# using sum()+ map()from itertools import chain# initializing listtest_list = [[3, True], [True, 6], [True, 9]]# printing original listprint("The original list is : " + str(test_list))# using sum()+ map()# Matrix True Summationres = sum(map(lambda i: i == True, chain.from_iterable(test_list)))# printing resultprint("The number of True elements: " + str(res)) |
The original list is : [[3, True], [True, 6], [True, 9]] The number of True elements: 3
Time complexity: O(n), where n is the total number of elements in the list “test_list”.
Auxiliary Space: O(1), as only a single integer value is stored in “res”.
Method #3 : Using extend()+count() methods
Step by step approach :
- Initialize a 2D list named test_list containing three inner lists.
- Print the original list using the print() function and concatenate the string “The original list is : ” with the list converted to a string using str().
- Create an empty list x to store all the elements of test_list.
- Iterate over each inner list i in test_list using a for loop.
- Extend the elements of i to the list x using the extend() method.
- Count the number of occurrences of True in the list x using the count() method and assign it to a variable named res.
- Print the result using the print() function and concatenate the string “The number of True elements: ” with the value of res converted to a string using str().
- End of program.
Python3
# Python 3 code to demonstrate# Matrix True Summation# initializing listtest_list = [[3, True], [True, 6], [True, 9]]# printing original listprint("The original list is : " + str(test_list))# Matrix True Summationx=[]for i in test_list: x.extend(i)res=x.count(True)# printing resultprint("The number of True elements: " + str(res)) |
The original list is : [[3, True], [True, 6], [True, 9]] The number of True elements: 3
Time Complexity: O(N)
Auxiliary Space: O(N)
Method #4 : Using numpy module
Note: Install numpy module using command “pip install numpy”
Python3
#Python 3 code to demonstrate#Matrix True Summation#using numpy moduleimport numpy as np#initializing listtest_list = [[3, True], [True, 6], [True, 9]]#printing original listprint("The original list is : " + str(test_list))#using numpy module#Matrix True Summationres = np.sum(np.array(test_list) == True)#printing resultprint("The number of True elements: " + str(res)) |
Output:
The original list is : [[3, True], [True, 6], [True, 9]] The number of True elements: 3
Time Complexity: O(n), where n is the number of elements in the matrix.
Auxiliary Space: O(n), as the numpy array is stored in memory.
Method 5: using nested loops
The approach is to use nested loops to iterate over the elements of the matrix and count the number of True values.
Python3
# initializing listtest_list = [[3, True], [True, 6], [True, 9]]# printing original listprint("The original list is : " + str(test_list))# using nested loops# Matrix True Summationcount = 0for row in test_list: for element in row: if element == True: count += 1# printing resultprint("The number of True elements: " + str(count)) |
The original list is : [[3, True], [True, 6], [True, 9]] The number of True elements: 3
Time Complexity: O(n), where n is the number of elements in the matrix.
Auxiliary Space: O(1)
Method #6 : Using opearor.countOf()
Approach
- Convert nested list to flatten list using extend() method
- Count the occurrence of True in flattened list using operator.countOf() method
- Display the count
Python3
# Python 3 code to demonstrate# Matrix True Summation# initializing listtest_list = [[3, True], [True, 6], [True, 9]]# printing original listprint("The original list is : " + str(test_list))# Matrix True Summationimport operatorx=[]for i in test_list: x.extend(i)res=operator.countOf(x,True)# printing resultprint("The number of True elements: " + str(res)) |
The original list is : [[3, True], [True, 6], [True, 9]] The number of True elements: 3
Time Complexity : O(N)
Auxiliary Space : O(1)
Method #7: Using the built-in reduce() function to count the number of True values
Step-by-step approach:
- Import the reduce() function from functools module.
- Initialize the list of lists to be tested.
- Define a lambda function that performs two operations. First, it maps the elements in the sublist to 1 if the element is True or 0 if it is False. Then, it sums the resulting list. The accumulator variable stores the sum of all the True values encountered so far.
- Call the reduce() function and pass it the lambda function defined in step 3, the list of lists to be tested, and an initial value of 0.
- Print the result.
Python3
# Python 3 code to demonstrate# Matrix True Summation# using reduce()from functools import reduce# initializing listtest_list = [[3, True], [True, 6], [True, 9]]# printing original listprint("The original list is : " + str(test_list))# using reduce()# Matrix True Summationres = reduce(lambda acc, sublist: acc + sum(map(lambda x: 1 if x == True else 0, sublist)), test_list, 0)# printing resultprint("The number of True elements: " + str(res)) |
The original list is : [[3, True], [True, 6], [True, 9]] The number of True elements: 3
Time complexity: O(nm) where n is the number of lists and m is the number of elements in each list.
Space complexity: O(1) as we are not using any extra space



