Find Average of Array Elements in Python
In this article, we will learn how to find the average of array elements using Python, along with examples to demonstrate the implementation. In this problem, we are given an array of integers, which may contain both positive and negative numbers. Our task is to calculate the average of all elements in the array.
Using the Brute Force Approach
This is a simple and direct approach. This approach involves manually iterating through each element in the array to calculate the sum. Then, we divide the total sum by the count of elements to get the average. This approach is more easier to understand but requires extra code.
Steps for Implementation
- Define a function to take the array as an input parameter.
- Initialize a variable sum to 0 for tracking the total sum of elements.
- Use a loop to traverse the array and calculate the total sum.
- Handle cases where the array is empty by returning 0.
- Return the sum divided by the count of elements to get the average.
def find_average(arr): if len(arr) == 0: return 0 total_sum = 0 for num in arr: total_sum += num return total_sum / len(arr) arr = [1, 3, 5, 7, 9] print("Average of array elements:", find_average(arr))Output
Average of array elements: 5.0
Using Python's Built-in sum() Function
In this approach, we use Python's built-in sum() function to simplify the calculation. The total sum of elements is obtained using sum(arr), and the length of the array is calculated using len(arr). This inbuilt() function makes it easy to calculate the sum without using the loop, only in one step.
Steps for Implementation
- Define a function and pass the array as a parameter.
- Use the sum() function to compute the total sum of elements.
- Handle the case where the array is empty by returning 0.
- Use the len() function to determine the count of elements.
- Return the average by dividing the total sum by the count.
def find_average(arr): if len(arr) == 0: return 0 total_sum = sum(arr) return total_sum / len(arr) arr = [-2, 4, -6, 8, 10] print("Average of array elements:", find_average(arr))Output
Average of array elements: 2.8
Using NumPy Library
NumPy is a popular library used for numerical computations. It provides a direct method, numpy.mean(), to calculate the average of given numbers. This method is better for large datasets and numerical applications. This approach is mainly used in large data science and machine learning applications. It provides additional functionalities like handling multi-dimensional arrays.
Steps for Implementation
- Import NumPy using import numpy as np.
- Use numpy.mean() to calculate the average of array elements.
- Handle cases where the array is empty.
import numpy as np def find_average(arr): if len(arr) == 0: return 0 return np.mean(arr) arr = [-4, 9, 16, -2, 7] print("Average of array elements:", find_average(arr))Output
Average of array elements: 5.2