I have a matrix (5,5) #empty matrix I want to add elements row-wise.
how to code to add elements to the next row if the previous row is full.
the first row is full and I want to add more elements but from the next row automatically
CodePudding user response:
This may be what you are after:
outer_matrix = [[None]*5 for i in range(5)]
def auto_add(element, matrix):
for row in range(len(matrix)):
for col in range(len(matrix[row])):
if matrix[row][col] == None:
# There is a free space, add element to it
matrix[row][col] = element
return matrix
for i in range(12):
outer_matrix = auto_add(i, outer_matrix)
>>> outer_matrix
[[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9],
[10, 11, None, None, None],
[None, None, None, None, None],
[None, None, None, None, None]]
If you are always using a 5 x 5
matrix, this is cleaner:
for row in range(5):
for col in range(5):