Search code examples
pythonlistmsemean-square-error

Python: How to access each element in list and put it into a new list


I am very new to python and I am trying to implement a MSE (Mean Squared Error) from my data. I am trying to access each element in the list and subtract the original data from the mean and square it at the end for the separate step so I can sum it up at the end and divide it by the total number of elements in the list.

For now, I am just trying to access each element in the list and find the difference and put it into the newly created list, newList.

Here is my current code:

for i in range(len(X)):
    newList[i] = X[i] - tempList[i]

at first, I tried doing

for i in range(len(X)):
    newList[i] = X[i] - mean

However, this gave me typeError saying that I cannot subtract float from list.

So I tried making a new list called tempList and put the mean value into the list by doing this:

for i in range(len(X)):
    tempList.insert(i, mean) #now my tempList contains [3.995, 3.995, 3.995 ....., 3.995]

Now it is giving me the same typeError:unsupported operand type(s) for -: 'list' and 'float'.

I am more familiar with java and other C languages and I thought that's the way you edit each element in the list, but I guess Python is different (obviously).

Any tips will be greatly appreciated.

Thanks in advance.


Solution

  • You have a problem elsewhere in the code, and that's why you're getting the type error. The snippets you showed are entirely legit.

        X = [ 2, 12, 85, 0, 6 ]
        tempList = [ 3, 4, 3, 1, 0 ]
        newList = list([0] * len(X))
    
        for i in range(len(X)):
            newList[i] = X[i] - tempList[i]
    
        print(newList)
    

    Anyhow, back to your original question, you can use functional style

        X = [ 2, 12, 85, 0, 6 ]
        mean = sum(X) / float(len(X))
        print(mean)
    
        Y = map(lambda x: x - mean, X)
        print(Y)