1

I am new to Python and coding in general and am struggling with this code:

I have 2 arrays:

actual_y = [10,20,30,40,50,60,70,80,90]
predicted_y = [1,2,3,4,5,6,7,8,9]

I want to create a for loop that will produce the difference between actual_y(i) and predicted_y(i).

I tried this:

for i in actual_y:
   for j in predicted_y:
      D = i - j
      print(D)

But I get an error when i run it. Any help is much appreciated!

  • 2
    what's the error? your code should work ok – eshirvana Jan 18 '22 at 19:55
  • You have nested loops so it iterates `len(actual_y) * len(predicted_y)` times. I think you just want one loop. However, your the code given shouldn't error. Please create a [mre] or add the error you are getting. – 001 Jan 18 '22 at 19:58
  • Does this answer your question? [How to iterate through two lists in parallel?](https://stackoverflow.com/questions/1663807/how-to-iterate-through-two-lists-in-parallel) – Tomerikoo Jan 18 '22 at 20:20

3 Answers3

6

this would be:

actual_y = [10,20,30,40,50,60,70,80,90]
predicted_y = [1,2,3,4,5,6,7,8,9]
difference = [i-j for i,j in zip(actual_y,predicted_y)]

print(abs(difference))

Output:

[9, 18, 27, 36, 45, 54, 63, 72, 81]
XxJames07-
  • 1,833
  • 1
  • 4
  • 17
2

alternatively you could use numpy :

import numpy as np
actual_y = np.array([10,20,30,40,50,60,70,80,90])
predicted_y = np.array([1,2,3,4,5,6,7,8,9])
print(actual_y - predicted_y)

output :

>>> [ 9 18 27 36 45 54 63 72 81]
eshirvana
  • 23,227
  • 3
  • 22
  • 38
1

The previous solution are fine, but if you still want to use the for loop, it may look like this.

actual_y = [10,20,30,40,50,60,70,80,90]
predicted_y = [1,2,3,4,5,6,7,8,9]


D = []
for i in range(0,len(actual_y)):
   B = actual_y[i] - predicted_y[i]
   D.append(B)
print(D)


[9, 18, 27, 36, 45, 54, 63, 72, 81]
Macosso
  • 1,352
  • 5
  • 22