How to find average of a list in Go

In Go, you can easily compute the average of a list of numbers using a straightforward approach that sums up the values and divides them by the total count. Calculating the average of a list is a fundamental operation in data analysis and statistics.

You can see here how to find the sum of a list in Go.

Code

The following code calculates the average of a list of numbers:

package main
import (
"fmt"
)
func calculateAverage(list []float64) float64 {
total := 0.0
for _, num := range list {
total += num
}
return total / float64(len(list))
}
func main() {
numbers := []float64{3.2, 5.8, 2.1, 9.7, 4.5}
avg := calculateAverage(numbers)
fmt.Printf("Average: %.2f\n", avg)
}

The calculateAverage function takes a slice of float64 values as input and uses a loop to accumulate the sum of all elements. By iterating through the list and adding each element to the total variable, the function finds the total sum of the array. The average is then computed by dividing the total sum by the count of elements in the list.

Time and space complexity

The algorithm's efficiency in terms of time and space is as follows:

Time complexity: The time complexity of this algorithm is O(n)O(n), where n is the number of elements in the list. The algorithm iterates through each element once to calculate the sum and then performs a constant-time division operation to find the average.

Space complexity: The space complexity of the algorithm is O(1)O(1), constant space. It only uses a fixed amount of memory to store the total sum and a few variables, regardless of the size of the list.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved