Python | Get first element with maximum value in list of tuples
Last Updated :
17 Apr, 2023
In Python, we can bind structural information in form of tuples and then can retrieve the same. But sometimes we require the information of tuple corresponding to maximum value of other tuple indexes. This functionality has many applications such as ranking. Let's discuss certain ways in which this can be achieved.
Method #1 : Using max() + operator.itemgetter() We can get the maximum of corresponding tuple index from a list using the key itemgetter index provided and then mention the index information required using index specification at the end.
Python3
# Python3 code to demonstrate
# to get tuple info. of maximum value tuple
# using max() + itemgetter()
from operator import itemgetter
# initializing list
test_list = [('Rash', 143), ('Manjeet', 200), ('Varsha', 100)]
# printing original list
print ("Original list : " + str(test_list))
# using max() + itemgetter()
# to get tuple info. of maximum value tuple
res = max(test_list, key = itemgetter(1))[0]
# printing result
print ("The name with maximum score is : " + res)
Output:Original list : [('Rash', 143), ('Manjeet', 200), ('Varsha', 100)]
The name with maximum score is : Manjeet
Time Complexity: O(n), where n is the length of the input list. This is because we’re using max() + operator.itemgetter() which has a time complexity of O(n) in the worst case.
Auxiliary Space: O(n), as we’re using additional space res other than the input list itself with the same size of input list.
Method #2 : Using max() + lambda This method is almost similar to the method discussed above, just the difference is the specification and processing of target tuple index for maximum is done by lambda function. This improved readability of code.
Python3
# Python3 code to demonstrate
# to get tuple info. of maximum value tuple
# using max() + lambda
# initializing list
test_list = [('Rash', 143), ('Manjeet', 200), ('Varsha', 100)]
# printing original list
print ("Original list : " + str(test_list))
# using max() + lambda
# to get tuple info. of maximum value tuple
res = max(test_list, key = lambda i : i[1])[0]
# printing result
print ("The name with maximum score is : " + res)
Output:Original list : [('Rash', 143), ('Manjeet', 200), ('Varsha', 100)]
The name with maximum score is : Manjeet
Method #3 : Using sorted() + lambda The task performed by the max() in the above two methods can be done using reverse sorting and printing the first element. lambda function performs the task similar to above said methods.
Python3
# Python3 code to demonstrate
# to get tuple info. of maximum value tuple
# using sorted() + lambda
# initializing list
test_list = [('Rash', 143), ('Manjeet', 200), ('Varsha', 100)]
# printing original list
print ("Original list : " + str(test_list))
# using sorted() + lambda
# to get tuple info. of maximum value tuple
res = sorted(test_list, key = lambda i: i[1], reverse = True)[0][0]
# printing result
print ("The name with maximum score is : " + res)
Output:Original list : [('Rash', 143), ('Manjeet', 200), ('Varsha', 100)]
The name with maximum score is : Manjeet
Method #4 : Using heapq module
One approach is using the heapq module. The heapq module provides an implementation of the heap queue algorithm, also known as the priority queue algorithm.
heapq is a python module that provides an implementation of the heap queue algorithm, also known as the priority queue algorithm. It allows you to efficiently find and extract the largest or smallest elements from a list, as well as insert new elements into the list in the correct order.
The nlargest function from heapq allows you to find the n largest elements from a list. It returns a list of the n largest elements in descending order.
Here is an example of how to use the heapq module to get the first element with the maximum value in a list of tuples:
Python3
import heapq
test_list = [('Rash', 143), ('Manjeet', 200), ('Varsha', 100)]
# Negate the values in the tuples to turn them into minimums
# and then use heapq.nlargest to get the smallest element
res = heapq.nlargest(1, [(v, k) for k, v in test_list])[0][1]
print("The name with the maximum score is:", res)
#This code is contributed by Edula Vinay Kumar Reddy
OutputThe name with the maximum score is: Manjeet
This approach has a time complexity of O(n log n) and a space complexity of O(n), where n is the number of tuples in the list.
Similar Reads
Python Tutorial | Learn Python Programming Language
Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced
Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions
Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs
Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Enumerate() in Python
enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
Python Data Types
Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Python Introduction
Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Lists
In Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe s
6 min read