0

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.

cohsta
  • 187
  • 1
  • 4
  • 14
  • How are you creating the X list? – Xorgon Oct 09 '17 at 22:53
  • @Xorgon X is a list of data with float list such as [[3.0],[2.5],[5.0],....,[1.5]] – cohsta Oct 09 '17 at 22:56
  • 2
    If that's the syntax you're using then that's the problem. In Python if something is in square brackets it is a list. So when you're doing X[i] it's returning another list. In that example X[0] = [3.0], which is a list of length 1 (X[0][0] = 3.0). Instead of doing that, simply define X as a float list with this syntax: [3.0, 2.5, 5.0, ... , 1.5]. – Xorgon Oct 09 '17 at 22:58
  • @Xorgon Yeah, as soon as I replied to you and I noticed my problem. However, after defining X as a float list with the syntax you mentioned, when I compile it, it gives me list assignment index out of range error :/ – cohsta Oct 09 '17 at 23:01
  • 2
    I would recommend looking at newList.append() for adding items to a list, rather than trying to reference a not yet existing list item. If you do list[0] = 1 on an empty list it will return an index out of range error. – Xorgon Oct 09 '17 at 23:02

1 Answers1

1

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)
Alex K
  • 34
  • 4