Home > Back-end >  What's wrong with my code? IndexError: list assignment index out of range
What's wrong with my code? IndexError: list assignment index out of range

Time:01-23

import math

rows = int(input())
cols = int(input())

room = [rows]
for i in range(rows):
  x = input()
  room[i] = [str(j) for j in x]
  print(room[i])

When I enter the input 3, 3, III, III, I get the error "IndexError: list assignment index out of range" following the second III. However, I don't see the issue... If it worked for the first III what's wrong with the second one?

CodePudding user response:

You cannot access not existing indexes, so one solution could be to init the room list as n empty list then grow the list each time you add an element with .append(...)

import math

rows = int(input())
cols = int(input())

room = []
for i in range(rows):
  x = input()
  room.append([str(j) for j in x])
  print(room[i])

Another solution could be to init the room list with as many Null values as expected rows.

import math

rows = int(input())
cols = int(input())

room = rows*[None]
for i in range(rows):
  x = input()
  room[i] = [str(j) for j in x]
  print(room[i])
  

CodePudding user response:

You are declaring room as a list with only only element, that being rows. On the first itteration of the for loop, you are writing to the first element of the list, wich overwrites the element with rows's content, but on the second itteration it will try to write to the second element, which does not exist, and throws an error.

If you are trying to add those value to the list use room.append (). This will add what ever you put inside the function to end of the list.

  •  Tags:  
  • Related