How to call Python max function using ‘key’ and lambda expression?

Sometimes, we want to call Python max function using ‘key’ and lambda expression.

In this article, we’ll look at how to call Python max function using ‘key’ and lambda expression.

How to call Python max function using ‘key’ and lambda expression?

To call Python max function using ‘key’ and lambda expression, we can call max with the list and the key argument set to a function that returns the value that we want to sort by.

For instance, we write

def func(p):
   return p.total_score

m = max(players, key=func)

to call max with the players list and the key set to the func function.

In func, we return the total_score function from the p object that’s in the players list to sort by the total_score value from each object in players and get the item with the max value of total_score.

Conclusion

To call Python max function using ‘key’ and lambda expression, we can call max with the list and the key argument set to a function that returns the value that we want to sort by.