Sum List Based on Function | Challenge

PythonPythonBeginner
Practice Now

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

Introduction

In Python, we can use the map() function to apply a function to each element of a list and return a new list with the modified values. We can also use the sum() function to calculate the sum of a list. In this challenge, you will need to write a function that takes a list and a function as arguments, maps each element of the list to a value using the provided function, and returns the sum of the values.


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-13191{{"`Sum List Based on Function | Challenge`"}} python/lists -.-> lab-13191{{"`Sum List Based on Function | Challenge`"}} python/tuples -.-> lab-13191{{"`Sum List Based on Function | Challenge`"}} python/dictionaries -.-> lab-13191{{"`Sum List Based on Function | Challenge`"}} python/function_definition -.-> lab-13191{{"`Sum List Based on Function | Challenge`"}} python/lambda_functions -.-> lab-13191{{"`Sum List Based on Function | Challenge`"}} python/build_in_functions -.-> lab-13191{{"`Sum List Based on Function | Challenge`"}} end

Sum List Based on Function

Problem

Write a function sum_by(lst, fn) that takes a list lst and a function fn as arguments. The function should map each element of the list to a value using the provided function, and return the sum of the values.

Example

sum_by([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], lambda v : v['n']) ## 20

In the example above, the sum_by() function takes a list of dictionaries and a lambda function that extracts the value of the 'n' key from each dictionary. The function maps each dictionary to its 'n' value and returns the sum of the values, which is 20.

Summary

In this challenge, you learned how to use the map() and sum() functions to calculate the sum of a list after mapping each element to a value using a provided function. This is a useful technique that can be used in many different scenarios, such as data processing and analysis.

Other Python Tutorials you may like