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 Find maximum element of each row in a matrix
Next article icon

Python program to Sort Matrix by Maximum Row element

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

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]] 
Output : [[10, 18, 3], [9, 10, 3], [0, 3, 5]] 
Explanation : 18, 10, and 5 are maximum elements in rows, hence sorted. 

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

In this, we perform task of sorting using sort() with key being maximum element from each row. The reverse keyword is used to sort by keeping maximum element rows at start and decreasing from there.

Python3




# Python3 code to demonstrate working of
# Sort Matrix by Maximum Row element
# Using sort() + max()
 
def max_sort(row):
    return max(row)
 
# initializing list
test_list = [[5, 7, 8], [9, 10, 3],
             [10, 18, 3], [0, 3, 5]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# sort() for sorting, max to get maximum values
test_list.sort(key = max_sort, reverse = True)
 
# printing result
print("The maximum sorted Matrix : " + str(test_list))
 
 

Output:

The original list is : [[5, 7, 8], [9, 10, 3], [10, 18, 3], [0, 3, 5]] The maximum sorted Matrix : [[10, 18, 3], [9, 10, 3], [5, 7, 8], [0, 3, 5]]

Time Complexity: O(nlogn) where n is the number of elements in the list “test_list”. 
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the list “test_list”. 

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

In this, we perform task of sorting using sorted() for non-inplace sort, and lambda function is used instead of external function to include maximum element from row logic.

Python3




# Python3 code to demonstrate working of
# Sort Matrix by Maximum Row element
# Using sorted() + lambda + max()
 
# initializing list
test_list = [[5, 7, 8], [9, 10, 3],
             [10, 18, 3], [0, 3, 5]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# sorted() for sorting, max to get maximum values
# reverse for reversed order
res = sorted(test_list, key = lambda row : max(row), reverse=True)
 
# printing result
print("The maximum sorted Matrix : " + str(res))
 
 

Output:

The original list is : [[5, 7, 8], [9, 10, 3], [10, 18, 3], [0, 3, 5]] The maximum sorted Matrix : [[10, 18, 3], [9, 10, 3], [5, 7, 8], [0, 3, 5]]

Method 3: Using a for loop

Step-by-step approach:

  • Initialize the given matrix test_list.
  • Iterate through each row of the matrix using a for loop.
  • For each row, find the maximum element using the max() function and store it in a list max_list.
  • Use the zip() function to pair the elements of max_list and test_list row-wise.
  • Sort the paired elements based on the values of max_list in descending order using the sorted() function and list comprehension.
  • Unzip the sorted pairs using the zip() function and store only the second element of each pair (i.e. the sorted rows of the matrix) in a list res.
  • Print the sorted matrix res.

Python3




# Python3 code to demonstrate working of
# Sort Matrix by Maximum Row element
# Using for loop + max() + sort()
 
# initializing list
test_list = [[5, 7, 8], [9, 10, 3],
             [10, 18, 3], [0, 3, 5]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# for loop to iterate through each row and store maximum element in a list
max_list = []
for row in test_list:
    max_list.append(max(row))
 
# sort matrix based on maximum values using zip()
res = [x for _, x in sorted(zip(max_list, test_list), reverse=True)]
 
# printing result
print("The maximum sorted Matrix : " + str(res))
 
 
Output
The original list is : [[5, 7, 8], [9, 10, 3], [10, 18, 3], [0, 3, 5]] The maximum sorted Matrix : [[10, 18, 3], [9, 10, 3], [5, 7, 8], [0, 3, 5]]

Time complexity: O(n^2) as we need to iterate through each element of the matrix and find the maximum element of each row.
Auxiliary space: O(n) to store the maximum values of each row in a list.



Next Article
Python Program to Find maximum element of each row in a matrix
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python Program to Find maximum element of each row in a matrix
    Given a matrix, the task is to find the maximum element of each row.Examples:  Input : [1, 2, 3] [1, 4, 9] [76, 34, 21] Output : 3 9 76 Input : [1, 2, 3, 21] [12, 1, 65, 9] [1, 56, 34, 2] Output : 21 65 56 Method 1: The idea is to run the loop for no_of_rows. Check each element inside the row and fi
    5 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 Tuples by their Maximum element
    Given a Tuple List sort tuples by maximum element in a tuple. Input : test_list = [(4, 5, 5, 7), (1, 3, 7, 4), (19, 4, 5, 3), (1, 2)] Output : [(19, 4, 5, 3), (4, 5, 5, 7), (1, 3, 7, 4), (1, 2)] Explanation : 19 > 7 = 7 > 2, is order, hence reverse sorted by maximum element. Input : test_list
    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 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 sort matrix based upon sum of rows
    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,
    6 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 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 - Sort by Maximum digit in Element
    Given a List of Elements, sort by the maximum digit of the element present in the List. Input : test_list = [234, 92, 8, 721] Output : [234, 721, 8, 92] Explanation : 4 < 7 < 8 < 9, sorted by maximum digits. Input : test_list = [92, 8, 721] Output : [721, 8, 92] Explanation : 7 < 8 <
    6 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
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