'List index out of range, but cannot find what is making it out of range

My Python code is throwing an exception here on this line, giving a "list index out of range" error, but I cannot find which part of my code is making i or r out of the array's range.

import time
import random
import math

sudoLine = [0,0,0]
possibleNums = [1,2,3]

print(len(possibleNums))

length = len(possibleNums) - 1
for i in range(3):
    r = random.randint(0,length)
    sudoLine[i] = possibleNums[r]
    possibleNums.pop(r)

print(sudoLine)

The error message is as follows:

  Message=list index out of range
  Source=C:\Users\heyma\source\repos\Sudoku Solver\Sudoku Solver\Sudoku_Solver.py
  StackTrace:
  File "C:\Users\heyma\source\repos\Sudoku Solver\Sudoku Solver\Sudoku_Solver.py", line 18, in <module> (Current frame)
    sudoLine[i] = possibleNums[r]

Sorry if this is a bad question, I'm fairly new as this is my first project!



Solution 1:[1]

The pop method removes an element from a list. So your possibleNums list is getting shorter with each iteration.

So at some point the value of r might be chosen to be greater that the current length of possibleNums.

Solution 2:[2]

This error is thrown because the length of the possibleNums list changed after pop command was issued. Therefore reducing the number of indexes.

import random

sudoLine = [0,0,0]
possible_nums = [1,2,3]
i = 0

while len(possible_nums) > 0:
  length = len(possible_nums) - 1
  r = random.randint(0, length)
  sudoLine[i] = possible_nums[r]
  possible_nums.pop(r)
  i += 1


print(sudoLine)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Arseny
Solution 2