Search code examples
pythonlistindex-error

define a 2d list in python


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 ?


Solution

  • 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.