title: Finding the nearest value and return the index of array in Python
body: <p>I found this post: <a href="https://stackoverflow.com/questions/604802/python-finding-an-element-in-an-array">Python: finding an element in an array</a></p>
  
  <p>and it's about returning the index of an array through matching the values.</p>
  
  <p>On the other hand, what I am thinking of doing is similar but different. I would like to find the nearest value for the target value. For example I am looking for 4.2 but I know in the array there is no 4.2 but I want to return the index of the value 4.1 instead of 4.4.</p>
  
  <p>What would be the fastest way of doing it?</p>
  
  <p>I am thinking of doing it the old way like how I used to do it with Matlab, which is using the array A where I want to get the index from to minus the target value and take the absolute of it, then select the min. Something like this:-</p>
  
  <pre><code>[~,idx] = min(abs(A - target))
  </code></pre>
  
  <p>That is Matlab code but I am newbie in Python so I am thinking, is there a fast way of doing it in Python?</p>
  
  <p>Thank you so much for your help!</p>