title: How come list index is out of range?
body: <p>I am working on a homework problem in which you have to find a missing number in an arithmetic progression. While the first sequence has no problem and indeed returns the right answer, the second one gives me an error </p>
  
  <p>"if sequence[i+1] != sequence[i] + difference:"</p>
  
  <p>"IndexError: list index out of range"</p>
  
  <pre><code>def find_missing(sequence):
      diff1 = sequence[1] - sequence[0]
      diff2 = sequence[2] - sequence[1]
      diff3 = sequence[3] - sequence[2]
      if diff1 == diff2:
          difference = diff1
      if diff2 == diff3:
          difference = diff3
      if diff1 == diff3:
          difference = diff1
      for i in sequence:
          if sequence[i+1] != sequence[i] + difference:
              return sequence[i] + difference
      return difference
  
  print(find_missing([1, 2, 3, 4, 6, 7, 8, 9]))
  print(find_missing([1, 3, 4, 5, 6, 7, 8, 9]))
  </code></pre>
  
  <p>Could anyone please explain to me how it is possible I am trying to access an element in a list which does not exist? 3 does not equal 1+difference(1), therefore it shoud just return 2. Please tell me what I am missing. Thank you.</p>