title: How to avoid IndexError: list index out of range for previous or next line
body: <p>I have a text file with lines, in order:</p>
  
  <pre><code>line 1 
  line 2 
  line 3
  line 4 
  line 5 
  </code></pre>
  
  <p>Now for example, if <code>line 4</code> exist in the text file, I need to display the previous or next word relative to <code>line 4</code> in order: previous is <code>line 3</code> next is <code>line 5</code> </p>
  
  <pre><code>data = open('file.txt', "r")
  searchlines = data.readlines()
  for q_numb, line in enumerate(searchlines):
      if ('line 4') in line:
          prev_line = searchlines[q_numb - 1]
          print ('"line 4" is found:',line, 'previous of "line 4" is:',prev_line)
          break
  data.close()
  </code></pre>
  
  <p>How do I avoid <code>IndexError: list index out of range</code> if <code>[q_numb - 1]</code> or <code>[q_numb + 1]</code> comes to an non-existent line? Should I just tell it to do something else, maybe somehow predict it? But how do I do that, how do I know to do something else if <code>-</code> or <code>+1</code> comes to a non-existent line? (For example, read only the current line in this case).</p>