title: Python: fastest list.index() operation USING 'is', not '==' (i.e. by reference)
body: <p>Question:</p>
  
  <p>In python, <code>list.index(a)</code> will return any index for which <code>a == list[index]</code> is true. But I need to find the index for which <code>a is list[index]</code>, and do so as quickly as possible (speed is vital). How would I go about doing so?</p>
  
  <p>Background:</p>
  
  <p>Maybe I am going about programming the wrong way. Just in case, here is the issue for which I need a solution to the above question: </p>
  
  <p>I have some text in which I must be able to insert/remove characters very quickly. Therefore, I use a list of the characters (about a million) instead of a string. </p>
  
  <p>Also, after any given insert/remove operation at an index, I must very quickly know how many newline characters precede that index. I have tried <code>list[0:index].count(newline)</code>, but it is to slow. So I am trying to a second approach using the solution to the above question. </p>
  
  <p>Of course, maybe this approach of working it out after every operation is too slow by definition. But I can't think of any fast way to maintain the information (for lookup, so I don't have to work it out every time) given that the indexes and amount of newlines can change every time I insert/remove a character.</p>
  
  <p>Edit:</p>
  
  <p>Here is approximately my solution until now. Using cProfile, I find it to take maybe 1/50 the time of doing <code>chars[0:index].count()</code>, but still not fast enough:</p>
  
  <pre><code>#Initialized once, and then maintained after every change.
  chars = [['\n'],['a'],['b'],['\n'],.... ]
  newlines = [newline for newline in chars if newline == ['\n']]
  
  #called every time I need the count of newlines preceding 'index'
  def newlinecount(index):
  
      #find closest preceding newline
      previousNewlineIndex = index
      while not chars[previousNewlineIndex ] == ['\n']:
          previousNewlineIndex -= 1
      previousNewline = chars[previousNewlineIndex]
  
      #find position of 'previousNewline' in 'newlines', and thus newlinecount
      for count, newline in enumerate(newlines):
          if newline is previousNewline:
              return count + 1 #(add 1 because 'count' starts from 0)
  </code></pre>
  
  <p>Thanks!</p>