Lilly001
Lilly001

Reputation: 1

How to make a matrix that only holds None values?

I have to write a function empty_matrix that must return a list of lists (a matrix)

desired output:

empty_matrix(3,4)

returns a list with three lists each of length four:

[[None,None,None,None],[None,None,None,None],[None,None,None,None]]

What should I change in my code below???

def empty_matrix(row,column):
first_col = []
for x in range(len(matrix)):
        sublist = matrix[x]
        for y in range(len(sublist)):
            first_col.append(matrix[x][y])

Upvotes: 0

Views: 280

Answers (1)

Jab
Jab

Reputation: 27485

Using a list comprehension:

def empty_matrix(row, column):
    return [[None for _ in range(row)] for _ in range(column)]

But to fix your code, you're using len on variables matrix and sublist that aren't defined, your indentation is off, try something like this if you don't want to use a list comprehension.

def empty_matrix(row, column):
    matrix = []
    for c in range(column):
        column = []
        for r in range(row):
            column.append(None)
        matrix.append(column)
    return matrix

Upvotes: 1

Related Questions