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 - Count the frequency of matrix row length
Next article icon

Python | Row lengths in Matrix

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

The problems concerning matrix are quite common in both competitive programming and Data Science domain. One such problem that we might face is of finding the lengths of rows of matrix in uneven sized matrix. Let’s discuss certain ways in which this problem can be solved. 

Method #1 : Using max() + map() + sum() + list comprehension The combination of above functions can help to get the solution to this particular problem in just a one line and hence quite useful. The sum function computes the sum of sublists, max function can be used to order in descending and all this bound together using list comprehension. 

Python3




# Python3 code to demonstrate
# Row lengths in matrix
# using max() + map() + sum() + list comprehension
 
# initializing list
test_list = [[4, 5, 6], [7, 8], [2]]
 
# printing original list
print("The original list : " + str(test_list))
 
# using max() + map() + sum() + list comprehension
# Row lengths in matrix
res = [sum(len(row) > idx for row in test_list)
    for idx in range(max(map(len, test_list)))]
 
# print result
print("The row lengths in matrix : " + str(res))
 
 
Output : 
The original list : [[4, 5, 6], [7, 8], [2]] The row lengths in matrix : [3, 2, 1]

Method #2 : Using sum() + filter() + zip_longest() This problem can also be solved using the set of functions above. The filter function can be used to get the separate lists and the task of binding for summation done by sum function is performed by zip_longest function. 

Python3




# Python3 code to demonstrate
# Row lengths in matrix
# using sum() + filter() + zip_longest()
from itertools import zip_longest
 
# initializing list
test_list = [[4, 5, 6], [7, 8], [2]]
 
# printing original list
print("The original list : " + str(test_list))
 
# using sum() + filter() + zip_longest()
# Row lengths in matrix
res = [sum(1 for idx in filter(None.__ne__, i))
              for i in zip_longest(*test_list)]
 
# print result
print("The row lengths in matrix : " + str(res))
 
 
Output : 
The original list : [[4, 5, 6], [7, 8], [2]] The row lengths in matrix : [3, 2, 1]

Method #3: Using for loop and append()

We can use a for loop to iterate over the rows of the matrix and append the length of each row to a new list.

Step by step Algorithm:

  • Initialize an empty list “res”.
  • Traverse through each row of the input list using a for loop.
  • Calculate the length of each row using the “len()” function.
  • Append the length of each row to the “res” list using the “append()” function.
  • Print the “res” list as the output.

Python3




# initializing list
test_list = [[4, 5, 6], [7, 8], [2]]
 
# printing original list
print("The original list : " + str(test_list))
 
# Using for loop and append()
# Row lengths in matrix
res = []
for row in test_list:
    res.append(len(row))
 
# print result
print("The row lengths in matrix : " + str(res))
 
 
Output
The original list : [[4, 5, 6], [7, 8], [2]] The row lengths in matrix : [3, 2, 1]

Time Complexity: O(n), where “n” is the total number of elements in the input list.
Auxiliary Space: O(n), where “n” is the total number of elements in the input list. This is because we are storing the length of each row in the “res” list.

Method #4: Using List Comprehension and len()

  • Initialize the original list
  • Use list comprehension to iterate over each sublist and compute its length using len() function
  • Store the length of each sublist in a new list using the list comprehension
  • Print the row lengths in matrix

Python3




## initializing list
test_list = [[4, 5, 6], [7, 8], [2]]
 
# printing original list
print("The original list : " + str(test_list))
 
# Using List Comprehension and len()
# Row lengths in matrix
res = [len(row) for row in test_list]
 
# print result
print("The row lengths in matrix : " + str(res))
 
 
Output
The original list : [[4, 5, 6], [7, 8], [2]] The row lengths in matrix : [3, 2, 1]

Time Complexity: O(n), where n is the number of sublists in the original list
Auxiliary Space: O(n), where n is the number of sublists in the original list



Next Article
Python - Count the frequency of matrix row length
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
  • Python matrix-program
Practice Tags :
  • python

Similar Reads

  • Python | Custom length Matrix
    Sometimes, we need to initialize a matrix in Python of variable length from the list containing elements. In this article, we will discuss the variable length method initialization and certain shorthands to do so. Let's discuss certain ways to perform this. Method #1: Using zip() + list comprehensio
    6 min read
  • Search Elements in a Matrix - Python
    The task of searching for elements in a matrix in Python involves checking if a specific value exists within a 2D list or array. The goal is to efficiently determine whether the desired element is present in any row or column of the matrix. For example, given a matrix a = [[4, 5, 6], [10, 2, 13], [1
    3 min read
  • Initialize Matrix in Python
    There are many ways to declare a 2 dimensional array with given number of rows and columns. Let us look at some of them and also at the small but tricky catches that accompany it. We can do it using list comprehension, concatenation feature of * operator and few other ways. Method 0: 2 list comprehe
    4 min read
  • Python - Count the frequency of matrix row length
    Given a Matrix, the task is to write a Python program to get the count frequency of its rows lengths. Input : test_list = [[6, 3, 1], [8, 9], [2], [10, 12, 7], [4, 11]] Output : {3: 2, 2: 2, 1: 1} Explanation : 2 lists of length 3 are present, 2 lists of size 2 and 1 of 1 length is present. Input :
    5 min read
  • Python program to omit K length Rows
    Given a Matrix, remove rows with length K. Input : test_list = [[4, 7], [8, 10, 12, 8], [10, 11], [6, 8, 10]], K = 2 Output : [[8, 10, 12, 8], [6, 8, 10]] Explanation : [4, 7] and [10, 11] omitted as length 2 rows. Input : test_list = [[4, 7], [8, 10, 12, 8], [10, 11], [6, 8, 10]], K = 3 Output : [[
    3 min read
  • Take Matrix input from user in Python
    Matrix is nothing but a rectangular arrangement of data or numbers. In other words, it is a rectangular array of data or numbers. The horizontal entries in a matrix are called as 'rows' while the vertical entries are called as 'columns'. If a matrix has r number of rows and c number of columns then
    5 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 | 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
  • 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 | Get Kth Column of Matrix
    Sometimes, while working with Python Matrix, one can have a problem in which one needs to find the Kth column of Matrix. This is a very popular problem in Machine Learning Domain and having solution to this is useful. Let's discuss certain ways in which this problem can be solved. Method #1 : Using
    6 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