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 | Row with Minimum element in Matrix
Next article icon

Python - Row with Maximum Record Element

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

Sometimes, while working with Python Records, we can have a problem in which we need to find the row with maximum record element. This kind of problem can come in domains of web development and day-day programming. Let's discuss certain ways in which this task can be performed.

Input : test_list = [[(70, 4), (6, 7)], [(15, 2), (19, 3)]] 
Output : [(70, 4), (6, 7)] 

Input : test_list = [[(20, 4)], [(15, 2)], [(34, 6)]] 
Output : [(34, 6)]

Method #1 : Using max() + key The combination of above functions can be used to solve this problem. In this, we extract maximum row using max() and key is used to check for initial element of records. 

Python3
# Python3 code to demonstrate working of  # Row with Maximum Record Element # Using max() + key  # initializing list test_list = [[(12, 4), (6, 7)],               [(15, 2), (19, 3)],               [(18, 3), (12, 4)],               [(17, 1), (11, 3)]]  # printing original list print("The original list is : " + str(test_list))  # Row with Maximum Record Element # Using max() + key res = max(test_list, key = max)  # printing result  print("The row with Maximum Value : " + str(res))  
Output : 

The original list is : [[(12, 4), (6, 7)], [(15, 2), (19, 3)], [(18, 3), (12, 4)], [(17, 1), (11, 3)]] The row with Maximum Value : [(15, 2), (19, 3)]

Time Complexity: O(n*n) where n is the number of elements in the list “test_list”. The max() + key is used to perform the task and it takes O(n*n) time.
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 max() + itemgetter() This is yet another way to solve this problem. This approach provides flexibility to make a choice on element index for comparison, rather than just initial as in above method by the usage of itemgetter(). 

Python3
# Python3 code to demonstrate working of  # Row with Maximum Record Element # Using max() + itemgetter() from operator import itemgetter  # initializing list test_list = [[(12, 4), (6, 7)],               [(15, 2), (19, 3)],               [(18, 3), (12, 4)],               [(17, 1), (11, 3)]]  # printing original list print("The original list is : " + str(test_list))  # Row with Maximum Record Element # Using max() + itemgetter() res = max(test_list, key = itemgetter(1))  # printing result  print("The row with Maximum Value : " + str(res))  
Output : 

The original list is : [[(12, 4), (6, 7)], [(15, 2), (19, 3)], [(18, 3), (12, 4)], [(17, 1), (11, 3)]] The row with Maximum Value : [(15, 2), (19, 3)]

Method #3 : Using max() + lambda function

In this approach, we use the max() function to find the sublist with maximum record element in the given list of sublists test_list. We pass a lambda function to max() as the key function to calculate the sum of the record elements in each sublist.

The sum(t[0] for t in x) expression in the lambda function calculates the sum of the first element in each tuple in the sublist x. If you have a different definition of "maximum record element", you can adjust the lambda function accordingly.

The max_sublist variable will contain the sublist with maximum record element. We then print the result using the print() function.

This approach is similar to the previous one, but uses a more concise lambda function.

Python3
# Sample list of sublists test_list = [[(20, 4)], [(15, 2)], [(34, 6)]]  # Find the sublist with maximum record element max_sublist = max(test_list, key=lambda x: sum(t[0] for t in x))  # Print the sublist with maximum record element print(max_sublist) 

Output
[(34, 6)]

The time complexity of this code is O(nm), where n is the length of test_list and m is the length of the longest sublist within test_list. This is because the max() function needs to iterate over each sublist in test_list, and the lambda function used as the key needs to sum the first elements of each tuple within each sublist. The lambda function has a time complexity of O(m) for each sublist, resulting in a worst-case time complexity of O(nm) for the entire function call.

The space complexity of this code is O(m), where m is the length of the longest sublist within test_list. This is because only a single sublist is stored in memory at a time, and the space required to store the max_sublist variable is proportional to the length of the longest sublist.

Method #4 :Using heapq:

  1. Import the heapq module
  2. Create a sample list of sublists test_list with tuples inside each sublist
  3. Use the heapq.nlargest() function to find the sublist with maximum record element
  4. The function takes three arguments:
  5. The number of sublists to return (in this case 1)
  6. The list to search (test_list)
  7. The key argument specifies a function of one argument to extract a comparison key from each sublist. Here,
  8. we sum the first element of each tuple in each sublist.
  9. The heapq.nlargest() function returns a list with the requested number of sublists sorted in descending order based on the key function.
  10. In this case, we request the largest sublist, so we extract the first (and only) element of the returned list using [0].
  11. Print the resulting sublist.
Python3
import heapq  # Sample list of sublists test_list = [[(20, 4)], [(15, 2)], [(34, 6)]] # printing original list print("The original list is : " + str(test_list))  # Find the sublist with maximum record element max_sublist = heapq.nlargest(1, test_list, key=lambda x: sum(t[0] for t in x))[0]  # Print the sublist with maximum record element print("The row with Maximum Value : "+str(max_sublist)) #This code is contributed by Jyothi Pinjala. 

Output
The original list is : [[(20, 4)], [(15, 2)], [(34, 6)]] The row with Maximum Value : [(34, 6)]

The time complexity : O(n log k), where n is the length of the input list and k is the number of elements to be returned. In this case, k is 1, so the time complexity is O(n log 1) = O(n).

The auxiliary space: O(k), as we are only keeping track of the k largest elements in the heap at any given time. In this case, k is 1, so the space complexity is O(1).

Method #5:Using reduce

Algorithm

  1. Initialize a variable max_sublist to the first sublist in the list.
  2. Iterate over each sublist in the list, comparing the record element sum of the current sublist with that of the max_sublist.
  3. If the record element sum of the current sublist is greater than that of max_sublist, set max_sublist equal to the current sublist.
  4. Return max_sublist.
Python3
from functools import reduce  # Sample list of sublists test_list = [[(20, 4)], [(15, 2)], [(34, 6)]]  # Find the sublist with maximum record element using reduce() max_sublist = reduce(lambda a, b: a if sum(t[0] for t in a) > sum(t[0] for t in b) else b, test_list)  # Print the sublist with maximum record element print(max_sublist) 

Output
[(34, 6)]

The time complexity of the algorithm for finding the sublist with the maximum record element in a list of sublists using iteration is O(n), where n is the number of sublists in the list. This is because the algorithm requires iterating over each sublist in the list once to compare their record element sums.

The auxiliary space of the algorithm is O(1), because the algorithm does not use any additional data structures that depend on the size of the input list. The algorithm only requires storing the current maximum sublist and the current sublist during the iteration, which are both constant-sized.


Next Article
Python | Row with Minimum element in Matrix
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • 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 - Dual Element row with Maximum difference
    Sometimes, while working with Python Matrix, we can have Matrix with its elements to be rows with just two elements and we may desire to get row with elements having maximum difference. This can have application in many domains. Lets discuss certain ways in which this task can be performed. Method #
    6 min read
  • Python - Maximum in Row Range
    Given a range and a Matrix, extract the maximum element out of that range of rows. Input : test_list = [[4, 3, 6], [9, 1, 3], [4, 5, 2], [9, 10, 3], [5, 9, 12], [3, 14, 2]], i, j = 2, 5 Output : 12 Explanation : Checks for rows 2, 3 and 4, maximum element is 12. Input : test_list = [[4, 3, 6], [9, 1
    5 min read
  • Python - Ranged Maximum Element in String List
    Sometimes, while working with Python data, we can have a problem in which we have data in form of String List and we require to find the maximum element in that data, but that also in a certain range of indices. This is quite peculiar problem but can have application in data domains. Let's discuss c
    5 min read
  • Python - Maximum Sum Record
    Sometimes, while working with data, we might have a problem in which we need to find maximum sum between available pairs in list. This can be application to many problems in mathematics domain. Let’s discuss certain ways in which this task can be performed. Method #1 : Using max() + list comprehensi
    3 min read
  • Keys with Maximum value - Python
    In Python, dictionaries are used to store data in key-value pairs and our task is to find the key or keys that have the highest value in a dictionary. For example, in a dictionary that stores the scores of students, you might want to know which student has the highest score. Different methods to ide
    4 min read
  • Python | Maximize Record list
    Sometimes, while working with Python records, we can have a problem in which we need to perform cross maximization of list of tuples. This kind of application is popular in web development domain. Let’s discuss certain ways in which this task can be performed. Method #1 : Using list comprehension +
    6 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 - Row with Maximum Product
    We can have an application for finding the lists with the maximum 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 - Remove rows with Numbers
    Given a Matrix, remove rows with integer instances. Input : test_list = [[4, 'Gfg', 'best'], ['gfg', 5, 'is', 'best'], [3, 5], ['GFG', 'Best']] Output : [['GFG', 'Best']] Explanation : All rows with numbers are removed. Input : test_list = [[4, 'Gfg', 'best'], ['gfg', 5, 'is', 'best'], [3, 5], ['GFG
    7 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