Home > Blockchain >  define a 2d list in python
define a 2d list in python

Time:11-29

rows = 7  
cols = 6  
mat = []  
for i in range(cols):
    col = []  
    for j in range(rows):
        col.append(0)  
    mat.append(col) 

for i in range(cols):  
    for j in range(rows):
        print(mat[j])
    print('\n')

why it has an //IndexError: list index out of range// error ?

CodePudding user response:

Either you can use

rows = 7  
cols = 6  
mat = []  
for i in range(cols):
    col = []  
    for j in range(rows):
        col.append(0)  
    mat.append(col) 

for i in range(cols):  
    for j in range(rows):
        print(mat[i][j], end = " ")
    print('\n')

Here you will print each values one by one. Or another method is just to print the entire row at once as:

rows = 7  
cols = 6  
mat = []  
for i in range(cols):
    col = []  
    for j in range(rows):
        col.append(0)  
    mat.append(col) 

for i in range(cols):  
    print(mat[i])
print('\n')

IndexError is because, you are trying to access an element which is not there.

CodePudding user response:

It is because of print(mat[j]) in the second for loop , you should write it in this form:

 print(mat[i][j]), end = " ")
print()
  • Related