I was creating a function to calculate the root mean square error (RMSE) between two lists (MSE wiki). For that, I need an element-wise subtraction of the lists. With the lists pred (predictions) and obs (observations), my first attempt was to use this:
se = [(p-0) for p in pred for o in obs]
but that resulted in a list of length n*n, with n the length of the original list. Eventually, I found out that
se = [(p-o) for p, o in zip(pred, obs)]
was the way to go, but now I'm curious why the first method doesn't work. Any ideas?
The first version uses a nested comprehension: Every element in pred
is paired with every element in obs
(length == n * m
).
zip
on the other hand, does an element-wise pairing like a zip (length == min(n, m)
).