How to Calculate the Sum and Average of Values in a 2D List Using Python

 

Have you ever wondered how to calculate the sum and average of values in a 2D list using Python?

 

If yes, let's explore a code practice together to achieve this!

 

Answer:

 

a = [[34,38,50,44,39],       [42,36,40,43,44],       [24,31,46,40,45],       [43,47,35,31,26],       [37,28,20,36,50]]     sum=0     for r in range(len(a)):     for c in range(len(a[r])):       sum = sum + a[r][c]     print("Sum of all values: " + str(sum) + "\n\n")   print("Average of all values: " + str(sum / (len(a) * len(a)))

 

In the given Python code practice, we are provided with a 2D list represented by the variable 'a'. The code snippet demonstrates how to calculate the sum and average of all the values present in the 2D list.

   

By iterating through each row and column of the 2D list, the code calculates the sum of all the values. It then proceeds to calculate the average by dividing the sum by the total number of elements in the 2D list.

   

After executing the code, you will see the output displaying the sum of all values and the average value.

   

Feel free to try running this code on your machine to practice calculating the sum and average of values in a 2D list using Python!

← Using my dict get key default what will this print Unlocking the mystery of open lockers →