A list is a data structure that allows you to store multiple variables or objects in a single variable. It is obvious that the list has many built-in functions for data manipulation. But while using without knowing you may get the error like ‘list’ object has no attribute ‘mean’. In this post you will learn how to solve the ‘list’ object has no attribute ‘mean’
What is the use of mean?
If you have datasets that contain the values of a number then you may require the mean to fill the row that has not data. Thus instead of keeping the data empty, you use the mean value there.
Why ‘list’ object has no attribute ‘mean’ Error comes?
There can be many reasons for getting this error. And the main reason is that you are using the wrong function mean(). The data structure list does not have a mean() inbuilt function.
Let’s say you have a list and want to find the mean of the list. If you run the below lines of code then you will get the AttributeError: ‘list’ object has no attribute ‘mean’
my_list = [10, 20, 30, 40, 50] my_list.mean()
AttributeError: 'list' object has no attribute 'mean'
The solution for ‘list’ object has no attribute ‘mean’
If you want to solve this problem then you have to properly use the mean function. The mean() function is builtin function for numpy package. If you want to compute the mean of all the elements of the list then you have to do it mathematically.
You will get the output when you will run the below lines of code.
my_list = [10, 20, 30, 40, 50] mean_value = sum(my_list) / len(my_list) print(mean_value)
But if you want to use the mean() function on the list then you have to follow the steps.
Step 1: Import the numpy package using the import statement.
import numpy as np
Step 2: First convert the list to numpy array
You can convert using the numpy.array() function. Just pass your list.
my_array = np.array(my_list)
Step 3: Use the mean() function
Now use the mean function to find the mean of the array.
mean_value = my_array.mean()
Step 4: Display the result
Lastly, use the print() function to print out the result.
In this tutorial you have learned why you were getting the ‘list’ object has no attribute ‘mean’ arrtibuteError. You have learned how to use the calculations to find the mean of the list. Also, find the mean of the list by first converting the list to numpy array and then using the numpy.mean() function on it.