Range index in list comprehension


I am surprise that list( the "total_loss2) comprehension doesn’t produce an index out of range error:

x = [1, 2, 3]
y = [5, 1, 3]
m2 = 0.5
b2 = 1
y_predicted2 = [values * m2 + b2 for values in x]

total_loss2 = 0
total_loss2 = sum([(y[i] - y_predicted2[i])**2 for i in range(len(x))])

while with a for loop, I must reduce len() to avoid it:

for i in range(len(x)-1):
  total_loss2 += (y[i] - y_predicted2[i])**2

What do I miss on that?

From what I can tell that’s not true, they’re both valid. Make sure you reinitialise any variables you change midway.

The range(len(x)) would be 0, 1, 2. Both y and y_predicted2 are three element lists. That all seems fine.

1 Like

Yes, both solutions works, the output is the same. Without the -1 or not…surely mess up with a variable somewhere.
Thanks for your time.

1 Like