I have a function that is supposed to increment each element in the odd rows of a matrix by 5, and each element in the even rows by 10. I have written the code below:
def incrementRows(matrix):
for i in matrix:
print(matrix.index(i))
if matrix.index(i) % 2 == 0:
matrix[matrix.index(i)] = [x + 5 for x in matrix[matrix.index(i)]]
else:
matrix[matrix.index(i)] = [x + 10 for x in matrix[matrix.index(i)]]
return matrix
matrix = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]]
print(incrementRows(matrix))
The problem with this code, is that judging by the print(matrix.index(i)) statement in the function, the loop never passes the first item in the list. I cannot understand why. Below is the output:
0
0
0
[[16, 17, 18, 19, 20], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]
If I take the If/else statements out of the function, then the loop will iterate through each item in the list properly.
def incrementRows(matrix):
for i in matrix:
print(matrix.index(i))
return matrix
matrix = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]]
print(incrementRows(matrix))
Result:
0
1
2
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]
Can anybody tell me why the If/else statements in the function are preventing the loop from iterating through each item in the list?