How to Calculate Average of Sub-lists in a List of Lists Using Python

How can we calculate the average of each sub-list in a list of lists using Python?

Let's dive into the step-by-step process to calculate the average values of sub-lists in a list of lists.

Solution: Calculating Average of Sub-lists in a List of Lists

To calculate the average of each sub-list in a list of lists using Python, you can follow these steps:

Step 1:

Initialize an empty list to store the average values.

Step 2:

Iterate over each sub-list in the main list.

Step 3:

Calculate the average of the current sub-list by summing up all elements and dividing by the length of the sub-list.

Step 4:

Append the computed average to the list of averages.

Step 5:

Return the list containing the average values of sub-lists in the same order as the input list.

Creating a function to calculate the average of sub-lists in a list of lists in Python involves using the accumulator pattern and processing nested lists with a for loop. By following the steps mentioned above, you can efficiently compute and return the average values.

The provided Python code snippet demonstrates the implementation of a function called `get_list_avg()` that accomplishes this task. It takes a parameter `main_list`, which is a list of lists, and returns a new list containing the average of each sub-list.

The function handles empty lists by returning an empty list as the result. It correctly computes the average by summing up elements in each sub-list and dividing by the length of the sub-list. This ensures that the order of the averages aligns with the order of sub-lists in the main list.

← Create a smart contract to manage multiple instructors in blockchain Roof truss uplift common causes and solutions →