title: python performance tips -- loop involving comparisons
body: <p>I am new to python and am trying to learn more about how it works by successively optimizing chunks of naive code I have already written. </p>
  
  <p>The following function involves a loop that performs operations on the elements of a list of list of floats only when the values of the data structure satisfy some condition. I was wondering if anyone could comment on (1) ways to improve the performance of this loop and (2) general features of the type of loop I'm describing that make it more or less suitable for different approaches to improving it. Below I've included a minimal version of the loop I'm working with.</p>
  
  <p>Some notes on the variables used below:</p>
  
  <pre><code>#p is a small integer (say, p=10)
  #index1 is an integer between 0 and p
  #k is an integer between 0 and, say, kmax=100
  #mat1 is a list of list of floats whose size is [kmax,p],
  #    with all values initialized to 0.0. 
  #    mat1 is changed by the loop below
  #mat2 is a list of list of floats whose size is [kmax,p]
  #    with all values initialized to -2e10. 
  #    mat2 is changed by other parts of the program 
  </code></pre>
  
  <p>Also, if it matters, in my code this is all part of a class, so there are "self." statements for the variables. I have read that local variables are handled better by python functions; how does this translate to class constructs?</p>
  
  <pre><code>def greatFunction(index1,k):                          
      index2 = index1
      for j in range(p):                        
          if (mat2[k][index2] &gt; -1e10):         
              mat1[k][j] = mat1[k][j] + mat2[k][index1]*mat2[k][index2]
          index2 = index2 - 1
          if(index2 &lt; 0):
              index2 = index2 + p
  </code></pre>
  
  <p>From what I have read I thought this would be a prime candidate for replacing the lists of lists with nparrays (in the class itself, not converting things in the function) and using masks to take care of the boolean conditions. However, the numpy version I wrote turned out to be slower than the vanilla python implementation above. Any help both speeding up the code but more importantly helping me understand why and how such loops can be replaced with a better construction would be much appreciated. Thank you!</p>