Monday, January 20, 2025
HomeProgrammingFinding the Average of a List - Python

Finding the Average of a List – Python

To calculate the average of a list in Python, you can use the built-in sum() and len() functions:

python
numbers = [12, 45, 78, 36, 45, 237.11, -1, 88]
average = sum(numbers) / len(numbers)
print(f"Average: {average:.2f}")

This method adds all elements in the list and divides by the number of elements.

Alternatively, Python’s statistics module provides a mean() function:

python
import statistics
numbers = [12, 45, 78, 36, 45, 237.11, -1, 88]
average = statistics.mean(numbers)
print(f"Average: {average:.2f}")

This function computes the mean directly.

For large datasets, consider using NumPy’s average() function for efficiency:

python
import numpy as np
numbers = [12, 45, 78, 36, 45, 237.11, -1, 88]
average = np.average(numbers)
print(f"Average: {average:.2f}")

This approach leverages NumPy’s optimized performance for numerical computations.

Choose the method that best fits your specific use case and data size.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x