Weighted Average Calculation Function

PythonPythonBeginner
Practice Now

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

Introduction

A weighted average is a type of average that takes into account the importance, or weight, of each value in a set of numbers. In this challenge, you will create a function that calculates the weighted average of a list of numbers.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-13741{{"`Weighted Average Calculation Function`"}} python/for_loops -.-> lab-13741{{"`Weighted Average Calculation Function`"}} python/lists -.-> lab-13741{{"`Weighted Average Calculation Function`"}} python/tuples -.-> lab-13741{{"`Weighted Average Calculation Function`"}} python/function_definition -.-> lab-13741{{"`Weighted Average Calculation Function`"}} python/build_in_functions -.-> lab-13741{{"`Weighted Average Calculation Function`"}} end

Weighted Average

Write a function weighted_average(nums, weights) that takes in two lists of equal length: nums and weights. The function should return the weighted average of the numbers in nums, where each number is multiplied by its corresponding weight in weights. The weighted average is calculated by dividing the sum of the products of each number and its weight by the sum of the weights.

def weighted_average(nums, weights):
  return sum(x * y for x, y in zip(nums, weights)) / sum(weights)
weighted_average([1, 2, 3], [0.6, 0.2, 0.3]) ## 1.72727

Summary

In this challenge, you learned how to calculate the weighted average of a list of numbers using Python. You used the sum() function to sum the products of the numbers by their weight and to sum the weights. You also used the zip() function and a list comprehension to iterate over the pairs of values and weights.

Other Python Tutorials you may like