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 Program to Sort the matrix row-wise and column-wise
Next article icon

Python program to sort matrix based upon sum of rows

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

Given a Matrix, perform sort based upon the sum of rows.

Input : test_list = [[4, 5], [2, 5, 7], [2, 1], [4, 6, 1]] 
Output : [[2, 1], [4, 5], [4, 6, 1], [2, 5, 7]] 
Explanation : 3 < 9 < 11 < 14. Sorted sum.

Input : test_list = [[4, 5], [2, 5, 7], [4, 6, 1]] 
Output : [[4, 5], [4, 6, 1], [2, 5, 7]] 
Explanation : 9 < 11 < 14. Sorted sum. 

Method #1 : Using sort() + sum()

In this, task of sorting is done using sort(), and computation of sum is done by sum(), and passed as key fnc. to sort().

Python3




# Python3 code to demonstrate working of
# Sort Matrix by row sum
# Using sort() + sum()
 
# helper_fnc
def sum_sort(row):
     
    # getting sum
    return sum(row)
 
# initializing list
test_list = [[4, 5], [2, 5, 7], [2, 1], [4, 6, 1]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using sort() to perform sort
test_list.sort(key = sum_sort)
 
# printing result
print("Sum sorted Matrix : " + str(test_list))
 
 

Output:

The original list is : [[4, 5], [2, 5, 7], [2, 1], [4, 6, 1]] 
Sum sorted Matrix : [[2, 1], [4, 5], [4, 6, 1], [2, 5, 7]]

Time Complexity: O(nlogn)
Auxiliary Space: O(1)

Method #2 : Using sorted() + sum() + lambda

In this, the task of sorting is done using sorted() and lambda is used in place of the external function call for the key.

Python3




# Python3 code to demonstrate working of
# Sort Matrix by row sum
# Using sorted() + sum() + lambda
 
# initializing list
test_list = [[4, 5], [2, 5, 7], [2, 1], [4, 6, 1]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using lambda function preventing fnc. call
res = sorted(test_list, key=lambda row: sum(row))
 
# printing result
print("Sum sorted Matrix : " + str(res))
 
 

Output:

The original list is : [[4, 5], [2, 5, 7], [2, 1], [4, 6, 1]] 
Sum sorted Matrix : [[2, 1], [4, 5], [4, 6, 1], [2, 5, 7]]

Time Complexity: O(n*nlogn) where n is the number of elements in the list “test_list”.  sorted() + sum() + lambda performs n*nlogn number of operations.
Auxiliary Space: O(1), no extra space is required 

Method #3 : Using the operator module and the sorted() function: 

Algorithm:

1.Initialize a list of sub-lists named ‘test_list’.
2.Import the operator module.
3.Sort the ‘test_list’ using the sorted() function and the operator module.
4.Use the ‘key’ parameter in the sorted() function to pass in the ‘operator.methodcaller’ function.
5.The ‘getitem’ method of the operator module returns the values of the sub-lists in the ‘test_list’.
6.The ‘slice(None)’ argument passed to ‘getitem’ method returns all the values of the sub-lists.
7.Store the sorted list in a variable named ‘res’.
8.Print the sorted list.

Python3




# importing operator module
import operator
 
# initializing list
test_list = [[4, 5], [2, 5, 7], [2, 1], [4, 6, 1]]
# printing original list
print("The original list is : " + str(test_list))
 
# using the operator module and the sorted() function
res = sorted(test_list, key=operator.methodcaller('__getitem__', slice(None)))
 
# printing result
print("Sum sorted Matrix : " + str(res))
#This code is contributed by Jyothi pinjala
 
 
Output
The original list is : [[4, 5], [2, 5, 7], [2, 1], [4, 6, 1]] Sum sorted Matrix : [[2, 1], [2, 5, 7], [4, 5], [4, 6, 1]]

Time complexity:
The time complexity of the sorted() function in the operator module is O(n log n), where ‘n’ is the number of sub-lists in the ‘test_list’.

Auxiliary Space:
The space complexity of this algorithm is O(n), where ‘n’ is the number of sub-lists in the ‘test_list’. This is because a new list is created to store the sorted list.

Method 4: Using the heapq module

  • Import the heapq module.
  • Initialize a list of sub-lists called test_list.
  • Print the original list of sub-lists.
  • Create an empty list called sorted_lists to store the sorted sub-lists.
  • Iterate over the range of the length of the test_list.
  • Use heapq.nsmallest() function to find the smallest sub-list based on the sum of its elements. This function takes two arguments, k and iterable. k is the number of smallest elements to return, and iterable is the list of sub-lists to search.
  • Append the smallest sub-list to the sorted_lists list.
  • Remove the smallest sub-list from the test_list.
  • Print the sorted list of sub-lists.

Python3




import heapq
 
# initializing list
test_list = [[4, 5], [2, 5, 7], [2, 1], [4, 6, 1]]
# printing original list
print("The original list is : " + str(test_list))
 
# creating an empty list to store the sorted sub-lists
sorted_lists = []
 
# iterating over the original list and finding the smallest sub-list based on the sum of its elements
for _ in range(len(test_list)):
    smallest = heapq.nsmallest(1, test_list, key=sum)
    sorted_lists.append(smallest[0])
    test_list.remove(smallest[0])
 
# printing the sorted list of sub-lists
print("Sum sorted Matrix : " + str(sorted_lists))
 
 
Output
The original list is : [[4, 5], [2, 5, 7], [2, 1], [4, 6, 1]] Sum sorted Matrix : [[2, 1], [4, 5], [4, 6, 1], [2, 5, 7]]

Time complexity: O(n log n), where n is the total number of elements in the original list. 
Auxiliary space: O(n), where n is the length of the original list.

Method 5: Use the built-in function min() and a custom comparison function

  1. Initialize a 2D list called test_list with 4 sub-lists of varying lengths and values.
  2. Print the original list using the print() function and the string concatenation operator +.
  3. Create an empty list called sorted_lists that will be used to store the sorted sub-lists.
  4. Define a comparison function compare_lists() that takes two sub-lists as input and returns the difference between their sums.
  5. Start a while loop that continues until the test_list is empty.
  6. Use the min() function with a lambda function as the key argument to find the smallest sub-list in the test_list based on the sum of its elements.
  7. If a smallest sub-list is found (i.e., it is not None), append it to the sorted_lists list using the append() method and remove it from the test_list using the remove() method.
  8. Repeat steps 6-7 until the test_list is empty.
  9. Print the sorted list of sub-lists using the print() function and string concatenation.

Python3




# initializing list
test_list = [[4, 5], [2, 5, 7], [2, 1], [4, 6, 1]]
# printing original list
print("The original list is : " + str(test_list))
 
# creating an empty list to store the sorted sub-lists
sorted_lists = []
 
# defining the comparison function
def compare_lists(list1, list2):
    return sum(list1) - sum(list2)
 
# iterating over the original list and finding the smallest sub-list based on the sum of its elements
while test_list:
    smallest = min(test_list, key=lambda x: sum(x), default=None)
    if smallest:
        sorted_lists.append(smallest)
        test_list.remove(smallest)
 
# printing the sorted list of sub-lists
print("Sum sorted Matrix : " + str(sorted_lists))
 
 
Output
The original list is : [[4, 5], [2, 5, 7], [2, 1], [4, 6, 1]] Sum sorted Matrix : [[2, 1], [4, 5], [4, 6, 1], [2, 5, 7]]

Time complexity: O(n^2 log n), where n is the total number of elements in the original list. 
Auxiliary space: O(n), since we need to store the sorted list of sub-lists.



Next Article
Python Program to Sort the matrix row-wise and column-wise
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python Program to Sort Matrix by Sliced Row and Column Summation
    Given a Matrix and a range of indices, the task is to write a python program that can sort a matrix on the basis of the sum of only given range of indices of each row and column i.e. the rows and columns are to sliced from a given start to end index, further, matrix are sorted using only those slice
    8 min read
  • Python program to Sort Matrix by Maximum Row element
    Given a Matrix, sort rows by maximum element. Input : test_list = [[5, 7, 8], [9, 10, 3], [10, 18, 3], [0, 3, 5]] Output : [[10, 18, 3], [9, 10, 3], [5, 7, 8], [0, 3, 5]] Explanation : 18, 10, 8 and 5 are maximum elements in rows, hence sorted. Input : test_list = [[9, 10, 3], [10, 18, 3], [0, 3, 5]
    4 min read
  • Python Program to sort rows of a matrix by custom element count
    Given Matrix, the following program shows how to sort rows of a matrix by the count of presence of numbers from a specified list. Input : test_list = [[4, 5, 1, 7], [6, 5], [9, 8, 2], [7, 1]], cus_list = [4, 5, 7] Output : [[9, 8, 2], [6, 5], [7, 1], [4, 5, 1, 7]] Explanation : 0 < 1 = 1 < 3 i
    5 min read
  • Python Program to Sort the given matrix
    Given a n x n matrix. The problem is to sort the given matrix in strict order. Here strict order means that matrix is sorted in a way such that all elements in a row are sorted in increasing order and for row ‘i’, where 1 <= i <= n-1, first element of row 'i' is greater than or equal to the la
    4 min read
  • Python Program to Sort the matrix row-wise and column-wise
    Given a n x n matrix. The problem is to sort the matrix row-wise and column wise.Examples: Input : mat[][] = { {4, 1, 3}, {9, 6, 8}, {5, 2, 7} } Output : 1 3 4 2 5 7 6 8 9 Input : mat[][] = { {12, 7, 1, 8}, {20, 9, 11, 2}, {15, 4, 5, 13}, {3, 18, 10, 6} } Output : 1 5 8 12 2 6 10 15 3 7 11 18 4 9 13
    4 min read
  • Python Program to Sort Matrix Rows by summation of consecutive difference of elements
    Given a Matrix, the following article depicts how to sort rows of a matrix on the basis of summation of difference between consecutive elements of a row. Input : test_list = [[1, 5, 3, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 2]], Output : [[4, 3, 2, 1], [7, 2, 4, 5], [1, 5, 3, 6], [6, 9, 3, 2]] Ex
    7 min read
  • Python Program to Find median in row wise sorted matrix
    We are given a row-wise sorted matrix of size r*c, we need to find the median of the matrix given. It is assumed that r*c is always odd.Examples: Input : 1 3 5 2 6 9 3 6 9Output : Median is 5If we put all the values in a sorted array A[] = 1 2 3 3 5 6 6 9 9)Input: 1 3 4 2 5 6 7 8 9Output: Median is
    5 min read
  • Python Program to Filter Rows with a specific Pair Sum
    Given Matrix, the following program shows how to extract all rows which have a pair such that their sum is equal to a specific number, here denoted as K. Input : test_list = [[1, 5, 3, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 2]], k = 8 Output : [[1, 5, 3, 6], [6, 9, 3, 2]] Explanation : 5 + 3 = 8
    6 min read
  • Python program to add two matrices
    Prerequisite : Arrays in Python, Loops, List Comprehension Program to compute the sum of two matrices and then print it in Python. We can perform matrix addition in various ways in Python. Here are a two of them. Examples: Input : X= [[1,2,3], [4 ,5,6], [7 ,8,9]] Y = [[9,8,7], [6,5,4], [3,2,1]] Outp
    2 min read
  • Python Program to print a specific number of rows with Maximum Sum
    Given a Matrix, the following article extracts a specifies number of rows that has a maximum sum. Input : test_list = [[3, 4, 5, 6], [1, 4, 6], [199], [2, 3, 4, 5, 6], [7, 3, 1]], K = 3  Output : [[199], [2, 3, 4, 5, 6], [3, 4, 5, 6]]  Explanation : 199 > 20 > 18, 3 maximum elements rows are e
    5 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