Average or Mean of a List In Python

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 83:-  Average or Mean of a List In Python

 

To calculate the average or mean of a list in Python, you can sum up all the elements in the list and then divide the sum by the number of elements in the list. Python provides several ways to achieve this, including using built-in functions, loops, and libraries like NumPy.

Here are a few examples of how to calculate the average of a list:

  1. Using Built-in Functions:

pythonCopy code

numbers = [10, 20, 30, 40, 50] # Using sum() and len() functions average = sum(numbers) / len(numbers) print(average)  # Output: 30.0

  1. Using a Loop:

pythonCopy code

numbers = [10, 20, 30, 40, 50] # Using a loop to calculate sum and count elements sum_numbers = 0 for num in numbers:    sum_numbers += num average = sum_numbers / len(numbers) print(average)  # Output: 30.0

  1. Using NumPy (with large datasets):

If you are working with large datasets or need to perform various mathematical operations, using the NumPy library can be more efficient.

pythonCopy code

import numpy as np numbers = [10, 20, 30, 40, 50] # Using NumPy's mean() function average = np.mean(numbers) print(average)  # Output: 30.0

Using NumPy provides a wide range of mathematical functions and can significantly speed up calculations for large datasets.

Keep in mind that the average can be a floating-point number even if all the elements in the list are integers. Python automatically performs floating-point division when dividing two integers if the result is not an integer. If you need the average to be an integer, you can use integer division (//) or convert the result to an integer using int(). However, this may result in loss of precision.

9. List

Comments: 0

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?