Problem: Given a list of objects, find the minimum and maximum value based on the class property in Python.

For Example, from a list of cars and find out which car has will come first and last in terms of their max speed.

To do this, we have to:

  1. Declare a class named Car with max_speed as one of its properties.
  2. Create a list of objects.
  3. Find the minimum and maximum of the objects on the basis of the max_speed property using the Python min() and max() methods.
#create class
class Car:
    def __init__(self, max_speed):
        self.name = name
        self.max_speed = max_speed

#create list of objects
cars_list = [Car('Nano', 258), Car('Ferrari', 337), Car('Maruti', 501)]

#use max() method to find car with max speed
first = max(cars_list, key=lambda car: car.max_speed)

#use min() method to find car with min speed
last = min(cars_list, key=lambda car: car.max_speed)

#output the results
print('Car with Maximum Speed: ',first.name)
print('Car with Minimum Speed: ',last.name)

Output:

Car with Maximum Speed: Maruti
Car with Minimum Speed: Nano

Leave a Reply

nineteen + 19 =