title: Using a for loop inline vs a nested for loop
body: <p>I am working on a function that takes in a test data set, compares the differences of each of the 62 points in the test set with each of the 248 points in the training set, determines which training data point is closest and uses that index to return an array of the predicted output. </p>
  
  <p>I get the function to work as shown below but I could not get it to work using a nested for loop. Can anybody explain to me why a nested for loop works differently? I am new to python and I have been struggling with this for a while.</p>
  
  <pre><code>def distance(x,y):
      return np.sum(np.abs(x-y))
  
  def NN_L1(trainx, trainy, testx):
      # inputs: trainx, trainy, testx &lt;-- as defined above
      # output: an np.array of the predicted values for testy 
  
      ### BEGIN SOLUTION
      predictions_l1 = np.ones(62)
      for j in range(len(testx)):
          prediction = trainy[np.argmin([distance(testx[j],trainx[i]) for i in range(len(trainx))])]
          predictions_l1[j] = prediction
      return predictions_l1
  </code></pre>
  
  <p>The nested for loop I was trying looks like this :</p>
  
  <pre><code>test_1 = np.ones(62)
  for j in range(len(testx)):
      for i in range(len(trainx)):
          tester = trainy[np.argmin([distance(testx[j], trainx[i])])]
  
  </code></pre>
  
  <p>I always get an array of identical values when I complete the function</p>