Syntax error Maximum value in record list as tuple attribute in Python

Maximum value in record list as tuple attribute in Python



When it is required to find the maximum value in a record list of tuples, the list comprehension and the 'max' methods can be used.

A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).

A list of tuple basically contains tuples enclosed in a list. The list comprehension is a shorthand to iterate through the list and perform operations on it.

The 'max' method can be used to find the maximum of all the elements in an iterable.

Below is a demonstration of the same −

Example

Live Demo

my_list = [('Will', [67, 45, 89]), ('Jam', [34, 56,13]), ('Pow', [99, 123, 89]), ('Nyk', [0, 56, 5])]

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

my_result = [(key, max(lst)) for key, lst in my_list]

print ("The maximum of list tuple attribute is : " )
print(my_result)

Output

The list of tuples is :
[('Will', [67, 45, 89]), ('Jam', [34, 56, 13]), ('Pow', [99, 123, 89]), ('Nyk', [0, 56, 5])]
The maximum of list tuple attribute is :
[('Will', 89), ('Jam', 56), ('Pow', 123), ('Nyk', 56)]

Explanation

  • A list of tuples is defined, and is displayed on the console.
  • The list comprehension is used to iterate through the list, and the maximum of the values in the tuple (inside the list of tuple) is obtained.
  • This operation's result is assigned to a variable.
  • It is then displayed on the console as the output.
Updated on: 2021-03-11T09:09:57+05:30

241 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements