Rui Yu Rui Yu - 9 days ago 7
Python Question

Create a list of lists. Modify elements in the list

Requirement:

Define the function createMatDimXDim (dim)
This function receives a positive integer number greater or equal than 2 and returns a square matrix of dimension dim x dim, where the contents are numbers which are equal to the row number multiplied by 10 plus the column number.

Expected output:

print (createMatDimXDim (4))
[[0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23], [30, 31, 32, 33]]


My code:

def createMatDimXDim (dim):
lis=[[0] for i in range(dim)]
for i in range(dim):
lis[i][0]=i*10
for i in range(dim):
lis[i].append(int(lis[i][0])+1)
return lis


Ouput of my code:

[[0, 1, 1, 1, 1], [10, 1, 11, 11, 11], [20, 1, 1, 21, 21], [30, 1, 1, 1, 31]]


I wanted to do this:

lis[i].append(int(lis[i][i-1])+1)


But it gives me an
IndexError

Answer
def createMatDimXDim (dim):
    lis=[[0] for i in range(dim)]
    for i in range(dim):
        lis[i][0]=i*10
        for j in range(dim-1):               # for the nested loop you need to use a new 
                                             # variable j
           lis[i].append(int(lis[i][j])+1)
    return lis

createMatDimXDim(4)
# [[0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23], [30, 31, 32, 33]]

Another option with list comprehension:

dim = 4
[[i * 10 + j for j in range(dim)] for i in range(dim)]
# [[0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23], [30, 31, 32, 33]]
Comments