title: Python- IndexError: list index out of range, while in for loop
body: <p>I'm new to python. I am trying to write a code to take input from text file like</p>
  
  <pre><code>6 6
  * o o o o *
  o o * o o o
  o o * o o *
  o o * o o o
  o o o o * o
  o o o o o o
  </code></pre>
  
  <p>and count the number of "*" near each string and update each string with the new count like:</p>
  
  <pre><code>6 6
  * 2 1 1 1 *
  1 3 * 2 2 2
  0 3 * 3 1 *
  0 2 * 2 2 2
  0 1 1 2 * 1
  0 0 0 1 1 1
  </code></pre>
  
  <p>And update this on an output.txt. Until now my code is taking input and providing rows, column, and matrix but as soon as I get into the list to count, it fails giving error</p>
  
  <blockquote>
  <pre><code>if matrix[num_rows][num_columns][1] == "x": 
  </code></pre>
    
    <p>IndexError: list index out of range</p>
  </blockquote>
  
  <p>My code snippet:</p>
  
  <pre><code>def parse_in(input_name):
      list_of_lists = []
      with open(input_name,"r") as f:
          for line in f:
              with open(input_name) as f:
                  num_rows, num_columns = [int(x) for x in next(f).split()]
  
                  lines = f.read().splitlines()
              # in alternative, if you need to use the file content as numbers
          matrix = []
          print(lines)
          for x in lines:
              matrix.append(x.split(' '))
          print(matrix)
      return matrix, num_rows, num_columns
  
  
  def detector(matrix, num_rows, num_columns):
      mine_count = 0
      # For every every space around the square, including itself
      for r in range(num_rows):
          for c in range(num_columns):
              # If the square exist on the matrix
              if 0 &lt;= num_rows + r &lt;= 2 and 0 &lt;= num_columns + c &lt;= 2:
                  # If the square contains a mine
                  if matrix[r][c] == "*":
                      # Raise the mine count
                      mine_count = mine_count + 1
              # If the original square contains a mine
              if matrix[r][c] == "*":
                  print(mine_count)
                  # Lower the mine count by 1, because the square itself having a mine shouldn't be counted
                  mine_count = mine_count - 1
                  print(mine_count)
              return mine_count
  
  
  def parse_out(output_name, my_solution):
      pass
  
  
  def my_main(input_name, output_name):
      # 1. We do the parseIn from the input file
      lines, num_rows, num_columns = parse_in(input_name)
  
      # 2. We do the strategy to solve the problem
      my_solution = detector(lines, num_rows, num_columns)
  
      # 3. We do the parse out to the output file
      parse_out(output_name, my_solution)
  
  
  if __name__ == '__main__':
      # 1. Name of input and output files
      input_name = "input_2.txt"
      output_name = "output.txt"
  
      # 2. Main function
      my_main(input_name, output_name)
  </code></pre>