Open In App

Python - Maximum of each Column

Last Updated : 13 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Sometimes, we are encountered such problems in which we need to find the maximum of each column in a matrix i.e maximum of each index in list of lists. This kind of problem is quite common and useful in competitive programming. Let’s discuss certain ways in which this problem can be solved.

Method #1: Using for loop+ max()


Output
The original list : [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
The Maximum of each index list is : [9, 7, 6]

Time Complexity: O(n),The above code iterates through the list once, hence the time complexity is linear, i.e. O(n).
Space Complexity: O(n),The algorithm uses an additional list to store the result, thus consuming linear space which is O(n).

Method #2: Using max() + list comprehension + zip()
The combination of above methods are required to solve this particular problem. The max function is used to get the required maximum value and zip function provides the combination of like indices and then list is created using list comprehension. 


Output
The original list : [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
The Maximum of each index list is : [9, 7, 6]

Time Complexity: O(n*n), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n), where n is the number of elements in the list “test_list”.

Method #3: Using map() + max() + zip()
This works in an almost similar way as the above method, but the difference is just that we use map function to build the max element list rather than using list comprehension. 


Output
The original list : [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
The Maximum of each index list is : [9, 7, 6]

Time Complexity: O(n*n), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n), where n is the number of elements in the list “test_list”.

Method #4: Using numpy()

Note: Install numpy module using command "pip install numpy"

Another approach to find the maximum of each column in a matrix can be using the numpy library.

Output:

The Maximum of each index list is: [9 7 6]
 

Time Complexity: O(m * n), where m is the number of rows and n is the number of columns in the matrix.
Auxiliary Space: O(n), where n is the number of elements in the result array.


Next Article
Practice Tags :

Similar Reads