pythonarrayslistindex-error

Getting an error name "index out of range" while playing around list in Python


I am a beginner and I am playing around a list where I have seen this error and got stuck. How can I fix it? What is the reason? Is there a solution?

row1 = ["😔", "😔", "😔"]
row2 = ["😔", "😔", "😔"]
row3 = ["😔", "😔", "😔"]
map = [row1 + row2 + row3]
print(f"{row1}\n{row2}\n{row3}\n")
position = input("Where do you want to put the treasures?")
row = int(position[0])
column = int(position[1])
map[row-1][column-1] = "x"
print(f"{row1}\n{row2}\n{row3}\n")

Output

 ['😔', '😔', '😔']
 ['😔', '😔', '😔']
 ['😔', '😔', '😔']

Where do you want to put the tresures?23
Traceback (most recent call last):
File "main.py", line 9, in <module>
map[row-1][column-1]="x"
IndexError: list index out of range

Solution

  • Your problem is in these lines:

    map=[row1+row2+row3]
    # and later:
    map[row-1][column-1]="x"
    

    When you are passing 23 as an input, the second line from above becomes:

    map[1][2]="x"
    

    map (as @DallogFheir pointed out) is a 2D array (list) with 1 row only

    map = [['😔', '😔', '😔', '😔', '😔', '😔', '😔', '😔', '😔']]
    

    This is because of the intialization of map as [row1+row2+row3]. So trying to access 2nd row is giving you that error.

    Solution: Change the first intialization to following:

    map=[row1,row2,row3]