1
elements = []
i,j = 0,0
while(i<3):
    while(j<3):
        elements[i][j] = int(input())
        j+=1
    i+=1
    j=0
print(elements) 

I'm trying to insert elements into 2 dimensional list by getting the input from the user. I'm unable to do so, its giving me a IndexError.

IndexError: list assignment index out of range

I'm expecting a 3x3 list. Something like :

elements = [
           [0,1,2],
           [3,4,5],
           [6,7,8]
           ]

What am I doing wrong here? [I do not wish to use Numpy or other libraries atm]

2 Answers2

0

This will sove your problem:

elements = []
i, j = 0,0

while(i<3):
    elements.append([])
    while(j<3):
        elements[i].append(int(input()))
        j+=1
    i+=1
    j = 0

print(elements)

The points:

  • Lists in python are not automatically appended when you access an index, you have to build the list.

  • You forgot to zero the "j" counter, so that it starts correctly in each row.

Cheers!

0

Problem with your case is that the list is initialized with size 0 and as a empty list. So, when you have to set value at some index it throws up error saying that the specified index is out of range because the index doesn't exist.

My approach mutates the existing list in-place or in other words appends a value.

Get size as input first

>>> rows = int(input("Enter no. of rows: "))
Enter no. of rows: 2
>>> cols = int(input("Enter no. of Columns: "))
Enter no. of Columns: 2

Create a list and loop through ranges

>>> l = []
>>> for i in range(rows):
...     row_vals = []
...     for j in range(cols):
...             row_vals.append(int(input(f"Enter value at {i}th row and {j}th column: ")))
...     l.append(row_vals)
... 
Enter value at 0th row and 0th column: 0
Enter value at 0th row and 1th column: 1
Enter value at 1th row and 0th column: 1
Enter value at 1th row and 1th column: 0
>>> l
[[0, 1], [1, 0]]
Vishnudev Krishnadas
  • 10,679
  • 2
  • 23
  • 55