Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Rear column in Multi-sized Matrix
Next article icon

Python - Uneven Sized Matrix Column Minimum

Last Updated : 01 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

The usual list of list, unlike conventional C type Matrix, can allow the nested list of lists with variable lengths, and when we require the minimum of its columns, the uneven length of rows may lead to some elements in that elements to be absent and if not handled correctly, may throw exception. Let’s discuss certain ways in which this problem can be performed in error-free manner. 

Method #1 : Using min() + filter() + map() + list comprehension 

The combination of above three function combined with list comprehension can help us perform this particular task, the min function helps to perform the minimum, filter allows us to check for the present elements and all rows are combined using the map function. Works only with python 2. 

Python
# Python code to demonstrate # Uneven Sized Matrix Column Minimum # using min() + filter() + map() + list comprehension  # initializing list of lists test_list = [[1, 5, 3], [4], [9, 8]]  # printing original list print("The original list is : " + str(test_list))  # using min() + filter() + map() + list comprehension # Uneven Sized Matrix Column Minimum res = [min(filter(None, j)) for j in map(None, *test_list)]  # printing result print("The minimum of columns is : " + str(res)) 
Output : 
The original list is : [[1, 5, 3], [4], [9, 8]] The minimum of columns is : [1, 5, 3]

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 #2: Using list comprehension + min() + zip_longest() 

If one desires not to play with the None values, one can opt for this method to resolve this particular problem. The zip_longest function helps to fill the not present column with 0 so that it does not have to handle the void of elements not present.

Python3
# Python3 code to demonstrate # Uneven Sized Matrix Column Minimum # using list comprehension + min() + zip_longest() import itertools  # initializing list of lists test_list = [[1, 5, 3], [4], [9, 8]]  # printing original list print("The original list is : " + str(test_list))  # using list comprehension + min() + zip_longest() # Uneven Sized Matrix Column Minimum res = [min(i) for i in itertools.zip_longest(*test_list, fillvalue=1000000)]  # printing result print("The minimum of columns is : " + str(res)) 
Output : 
The original list is : [[1, 5, 3], [4], [9, 8]] The minimum of columns is : [1, 5, 3]

Time complexity: O(n*m), where n is the number of sublists in the main list and m is the length of the longest sublist. 
Auxiliary space: O(m), where m is the length of the longest sublist. 

Method#3: Using enumerate

Approach:

  1. Define a function min_column which takes a matrix as input. Initialize a list min_col with an infinite value for each column, this will serve as a temporary holder for the minimum values of each column. 
  2. Loop through each row in the matrix. 
  3. For each row, loop through each column using enumerate() function to access both the index and value of the current column. 
  4. If the current column value is less than the value in min_col for that column index, update the value in min_col with the current column value. 
  5. After all, rows have been processed, return the min_col list, which will contain the minimum value for each column in the matrix.

Algorithm

  1. Initialize a list min_col with the first row's length and assign each element to float('inf').
  2. Traverse through each row of the matrix and get the column value at each index of that row.
  3. Compare the column value with the corresponding element in the min_col list and update the element in min_col if it is greater than the column value.
  4. Return the min_col list as the output.
Python3
def min_column(matrix):      # initialize with first row length     min_col = [float('inf')] * len(matrix[0])      for row in matrix:         for i, col_val in enumerate(row):             if col_val < min_col[i]:                 min_col[i] = col_val      return min_col  # Testing the function   # Input list matrix = [[1, 5, 3], [4], [9, 8]]  # Print the answer print("The original matrix is :", matrix) print("The minimum of columns is :", min_column(matrix)) 

Output
The original matrix is : [[1, 5, 3], [4], [9, 8]] The minimum of columns is : [1, 5, 3]

Time Complexity: O(N * M), where n is the number of rows and m is the number of columns in the matrix.
Auxiliary Space: O(M), where m is the number of columns in the matrix. This is because we are only storing the min_col list, which has m elements.

Method#4: Using def 

Approach:

This implementation first finds the maximum number of columns in the matrix, and then for each column index i, it creates a list of values at index i from each row that has at least i+1 columns. It then takes the minimum value from this list and appends it to the result list.

Algorithm:

  1. Define a function column_minimum that takes a matrix as input.
  2. Initialize an empty list to store the minimum values for each column.
  3. Iterate over a range of column indices, from 0 up to the maximum length of any row in the matrix.
  4. Use a list comprehension to find the minimum value for the current column by iterating over the rows and selecting the values at the current column index.
  5. Append the minimum value to the list of minimum values.
  6. Return the list of minimum values.
Python3
def column_minimum(matrix):     return [min([row[i] for row in matrix if len(row) > i]) for i in range(len(max(matrix, key=len)))]  test_list = [[1, 5, 3], [4], [9, 8]] print("The minimum of columns is :", column_minimum(test_list)) 

Output
The minimum of columns is : [1, 5, 3]

The time complexity of this implementation is O(n^2) where n is the number of rows in the matrix, since we are iterating over each row and each column. The auxiliary space is O(n) since we are storing a list of length n for the result.

Method#5: Using heapq:

Algorithm:

  1. Import heapq and itertools modules.
  2. Initialize a list of lists, test_list, with some data.
  3. Print the original matrix.
  4. Define res using list comprehension and itertools.zip_longest().
  5. Use heapq.nsmallest to find the minimum value of each column. If a column contains None values (i.e. it is
  6. shorter than the other columns), use filter to remove these values before finding the minimum.
  7. Print the resulting list of minimum values.
Python3
import heapq import itertools  # initializing list of lists test_list = [[1, 5, 3], [4], [9, 8]] print("The original matrix is :", test_list)  # using heapq + zip_longest() # Uneven Sized Matrix Column Minimum res = [heapq.nsmallest(1, filter(lambda x: x is not None, i))[0]        for i in itertools.zip_longest(*test_list, fillvalue=1000000)]  # printing result print("The minimum of columns is : " + str(res))  # This code is contributed by Jyothi pinjala. 

Output
The original matrix is : [[1, 5, 3], [4], [9, 8]] The minimum of columns is : [1, 5, 3]

Time complexity: O(mn log k) where m is the number of rows, n is the number of columns, and k is the length of the longest row. heapq.nsmallest() method has time complexity O(klogk), and the list comprehension iterates over all columns and rows, taking O(mn) time. The zip_longest method runs in O(mn) time in the worst case.

Space complexity: O(mn) for storing the test_list, plus O(k) for the res list created by list comprehension, and O(k) additional space for the fillvalue. Overall, space complexity is O(mn).

Method #6: Using numpy 

Python3
import numpy as np  # initializing list of lists test_list = [[1, 5, 3], [4], [9, 8]] print("The original matrix is :", test_list)  # using numpy max_len = max(len(sublist) for sublist in test_list) arr = np.array([sublist + [1000000] * (max_len - len(sublist)) for sublist in test_list]) res = np.min(arr, axis=0)  # printing result print("The minimum of columns is: " + str(res)) 
Output: The original matrix is : [[1, 5, 3], [4], [9, 8]] The minimum of columns is : [1, 5, 3]

Time complexity of O(n), where n is the total number of elements in the matrix.
Auxiliary space complexity of O(n) as well.


Next Article
Python - Rear column in Multi-sized Matrix
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python - Rear column in Multi-sized Matrix
    Given a Matrix with variable lengths rows, extract last column. Input : test_list = [[3, 4, 5], [7], [8, 4, 6], [10, 3]] Output : [5, 7, 6, 3] Explanation : Last elements of rows filtered. Input : test_list = [[3, 4, 5], [7], [8, 4, 6]] Output : [5, 7, 6] Explanation : Last elements of rows filtered
    4 min read
  • Python - Column Minimum in Tuple list
    Sometimes, while working with records, we can have a problem in which we need to find min of all the columns of a container of lists which are tuples. This kind of application is common in web development domain. Let’s discuss certain ways in which this task can be performed. Method #1 : Using min()
    6 min read
  • Python - Row with Minimum Sum in Matrix
    We can have an application for finding the lists with the minimum value and print it. This seems quite an easy task and may also be easy to code, but having shorthands to perform the same are always helpful as this kind of problem can come in web development. Method #1 : Using reduce() + lambda The
    4 min read
  • Python | Minimum Difference in Matrix Columns
    This particular article focuses on a problem that has utility in competitive as well as day-day programming. Sometimes, we need to get the minimum difference between the like indices when compared with the next list. The minimum difference between the like elements in that index is returned. Let’s d
    3 min read
  • Summation Matrix columns - Python
    The task of summing the columns of a matrix in Python involves calculating the sum of each column in a 2D list or array. For example, given the matrix a = [[3, 7, 6], [1, 3, 5], [9, 3, 2]], the goal is to compute the sum of each column, resulting in [13, 13, 13]. Using numpy.sum()numpy.sum() is a hi
    2 min read
  • Python | Row with Minimum element in Matrix
    We can have an application for finding the lists with the minimum value and print it. This seems quite an easy task and may also be easy to code, but sometimes we need to print the entire row containing it and having shorthands to perform the same are always helpful as this kind of problem can come
    5 min read
  • Python - Column Maximum in Dictionary Value Matrix
    Given a Dictionary with Matrix Values, compute maximum of each column of those Matrix. Input : test_dict = {"Gfg" : [[7, 6], [3, 2]], "is" : [[3, 6], [6, 10]], "best" : [[5, 8], [2, 3]]} Output : {'Gfg': [7, 6], 'is': [6, 10], 'best': [5, 8]} Explanation : 7 > 3, 6 > 2, hence ordering. Input :
    5 min read
  • Python | Search in Nth Column of Matrix
    Sometimes, while working with Python Matrix, we can have a problem in which we need to check if an element is present or not. This problem is simpler, but a variation to it can be to perform a check in a particular column of Matrix. Let's discuss a shorthand by which this task can be performed.  Met
    10 min read
  • Python - Sort Matrix by Maximum String Length
    Given a matrix, perform row sort basis on the maximum length of the string in it. Input : test_list = [['gfg', 'best'], ['geeksforgeeks'], ['cs', 'rocks'], ['gfg', 'cs']] Output : [['gfg', 'cs'], ['gfg', 'best'], ['cs', 'rocks'], ['geeksforgeeks']] Explanation : 3 < 4 < 5 < 13, maximum leng
    3 min read
  • Python - Sort Matrix by K Sized Subarray Maximum Sum
    Given Matrix, write a Python program to sort rows by maximum of K sized subarray sum. Examples: Input : test_list = [[4, 3, 5, 2, 3], [6, 4, 2, 1, 1], [4, 3, 9, 3, 9], [5, 4, 3, 2, 1]], K = 3 Output : [[4, 3, 5, 2, 3], [6, 4, 2, 1, 1], [5, 4, 3, 2, 1], [4, 3, 9, 3, 9]] Explanation : 12 = 12 = 12
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences