Find Maximum List Value Based on Function

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In Python, we can use the max() function to find the maximum value in a list. However, what if we want to find the maximum value after mapping each element to a value using a provided function? In this challenge, you will need to write a function that takes a list and a function as arguments, maps each element to a value using the provided function, and returns the maximum value.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/dictionaries("`Dictionaries`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/lambda_functions("`Lambda Functions`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-13686{{"`Find Maximum List Value Based on Function`"}} python/lists -.-> lab-13686{{"`Find Maximum List Value Based on Function`"}} python/tuples -.-> lab-13686{{"`Find Maximum List Value Based on Function`"}} python/dictionaries -.-> lab-13686{{"`Find Maximum List Value Based on Function`"}} python/function_definition -.-> lab-13686{{"`Find Maximum List Value Based on Function`"}} python/lambda_functions -.-> lab-13686{{"`Find Maximum List Value Based on Function`"}} python/build_in_functions -.-> lab-13686{{"`Find Maximum List Value Based on Function`"}} end

Find Maximum List Value Based on Function

Write a function max_by(lst, fn) that takes a list lst and a function fn as arguments. The function should map each element in lst to a value using the provided function fn, and then return the maximum value.

def max_by(lst, fn):
  return max(map(fn, lst))
max_by([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], lambda v : v['n']) ## 8

Summary

In this challenge, you have learned how to find the maximum value in a list after mapping each element to a value using a provided function. You have written a function max_by(lst, fn) that takes a list and a function as arguments, maps each element to a value using the provided function, and returns the maximum value.

Other Python Tutorials you may like