Python – Get the object with the max attribute value in a list of objects
Last Updated :
14 Feb, 2023
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 geeks 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 geeks:
def __init__( self , experience, salary):
self .experience = experience
self .salary = salary
object1 = geeks( 2 , 50000 )
object2 = geeks( 3 , 60000 )
object3 = geeks( 1 , 20000 )
object4 = geeks( 4 , 75000 )
l = [object4, object3, object2, object1]
max_attr = max (l, key = attrgetter( 'salary' ))
print (max_attr.salary)
|
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 geeks:
def __init__( self , experience, salary):
self .experience = experience
self .salary = salary
object1 = geeks( 7 , 57050 )
object2 = geeks( 3 , 98000 )
object5 = geeks( 6 , 45000 )
object4 = geeks( 1 , 89000 )
object3 = geeks( 5 , 25000 )
l = [object4, object3, object5, object2, object1]
max_attr = max (l, key = attrgetter( 'salary' ))
print (max_attr.salary)
|
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
class geeks:
def __init__( self , experience, salary):
self .experience = experience
self .salary = salary
object1 = geeks( 2 , 50000 )
object2 = geeks( 3 , 60000 )
object3 = geeks( 1 , 20000 )
object4 = geeks( 4 , 75000 )
l = [object4, object3, object2, object1]
max_attr = max (l, key = lambda x: x.salary)
print (max_attr.salary)
|
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)
Share your thoughts in the comments
Please Login to comment...