Index minimum value Record in Python

PythonServer Side ProgrammingProgramming

If it is required to find the tuple corresponding to the minimum value of other tuple index, it can be done using the 'min' method, and the 'operator.itemgetter' method.

The 'min' method gives the minimum of the elements in the iterable. The itemgetter fetches a specific item from its operand.

Below is a demonstration of the same −

Example

Live Demo

from operator import itemgetter
my_list = [('Will', 45), ('Jam', 13), ('Pow', 89), ('Nyk', 56)]

print ("The list is: " )
print(my_list)

my_result = min(my_list, key = itemgetter(1))[0]

print ("The value with minimum score is : " )
print(my_result)

Output

The list is:
[('Will', 45), ('Jam', 13), ('Pow', 89), ('Nyk', 56)]
The value with minimum score is :
Jam

Explanation

  • The required packages are imported.
  • A list of tuples is defined, and is displayed on the console.
  • The 'min' function is applied on this list of tuples, with the key as the itemgetter.
  • This itemgetter helps fetch a specific item from the operand.
  • This value is assigned to a variable.
  • This variable is the output, which is displayed on the console.
raja
Published on 11-Mar-2021 09:09:39
Advertisements