How to search list of objects for index of minimum
You can use min
's key
argument to search by index:
index = min(range(len(schools)), key=lambda i: schools[i].students_per_class())
print(schools[index])
A key provides the values that will be compared instead of the actual sequence. Here, my sequence is range(len(schools))
, which is just the indices of all the elements. But instead of finding the minimum index, I am making it so that we find the minimum of schools[i].students_per_class()
for each index i
.
If you wanted to be able to compare, sort, find the min/ max on the items directly you could use the "dunder" methods. These methods allow you to overload built in functions on classes.
For instance if you had a class like this
class Item:
def __init__(self, value):
self.value = value
def __lt__(self, other):
return self.value < other.value
def __eq__(self, other):
return self.value == other.value
You can then create two instances and compare them directly like this,
A = Item(1)
B = Item(2)
print(A < B) # Prints True
or if you had a list of items
items = [A, B]
You can then get the minimum item by going
min_item = min(items)
or the index of it by going
min_item_index = items.index(min(items))
although it may be enough to just have a reference to the minimum item.