Given a list of objects, the task is to write a Python program to get the object with the max attribute value in a list of objects using Python.
This task can be achieved by using the max() method and attrgetter operator. It returns a callable object that fetches attr from its operand. If more than one attribute is requested, returns a tuple of attributes. The attribute names can also contain dots.
Syntax:
attrgetter(attr)
To get the job done, define a class and define a __init__() method. Then, initialize the instance variables for example salary and experience. Now, create multiple instances/ Objects for the Lazyroar class and append all the objects into a list. Now pass the list of objects to the max() method with key=attribute, The attribute can be given using the attrgetter operator.
The max() method will return the object with max attribute value.
Example 1: Get the object with max attribute value in a list of objects
Python3
from operator import attrgetter class Lazyroar: def __init__( self , experience, salary): self .experience = experience self .salary = salary object1 = Lazyroar( 2 , 50000 ) object2 = Lazyroar( 3 , 60000 ) object3 = Lazyroar( 1 , 20000 ) object4 = Lazyroar( 4 , 75000 ) l = [object4, object3, object2, object1] max_attr = max (l, key = attrgetter( 'salary' )) print (max_attr.salary) |
75000
Time Complexity: O(n), where n is the total number of objects in the list.
Auxiliary Space: O(1)
Example 2: Get the object with a max attribute value in a list of objects
Python3
from operator import attrgetter class Lazyroar: def __init__( self , experience, salary): self .experience = experience self .salary = salary object1 = Lazyroar( 7 , 57050 ) object2 = Lazyroar( 3 , 98000 ) object5 = Lazyroar( 6 , 45000 ) object4 = Lazyroar( 1 , 89000 ) object3 = Lazyroar( 5 , 25000 ) l = [object4, object3, object5, object2, object1] max_attr = max (l, key = attrgetter( 'salary' )) print (max_attr.salary) |
98000
Time Complexity: O(n), where n is the total number of objects in the list.
Auxiliary Space: O(1)
Here is another approach to finding the object with the maximum attribute value in a list of objects in Python:
Python3
# Using a lambda function class Lazyroar: def __init__( self , experience, salary): self .experience = experience self .salary = salary object1 = Lazyroar( 2 , 50000 ) object2 = Lazyroar( 3 , 60000 ) object3 = Lazyroar( 1 , 20000 ) object4 = Lazyroar( 4 , 75000 ) l = [object4, object3, object2, object1] max_attr = max (l, key = lambda x: x.salary) print (max_attr.salary) |
75000
In this approach, we are using a lambda function to extract the salary attribute from each object and pass it to the key parameter of the max() function. The lambda function takes an argument x, which is an object from the list, and returns x.salary.
Time Complexity: O(n), where n is the total number of objects in the list.
Auxiliary Space: O(1)