Multiple ways to do it:
- Fix your method. In Python, lists are zero-based so you need to only iterate from
i = 0
to len(matrix) - 1
. Doing for i in range(len(matrix)):
does this for you. You don't need to do range(len(matrix) + 1))
. Also, you should only replace the current maxval if the element you're looking at is greater than maxval
.
So,
maxval = -9999999
for i in range(len(matrix)):
for j in range(len(matrix[i])):
if matrix[i][j] > maxval:
maxval = matrix[i][j]
print(maxval)
# Out: 10
Or, a more pythonic way is to iterate over the elements instead of accessing them through their indices
maxval = -9999999
for row in matrix:
for element in row:
if element > maxval:
maxval = element
# maxval: 10
Notice I use maxval
instead of max
so as not to shadow python's inbuilt max()
function.
- Use numpy (if you're already using it for other things). Like wim mentioned in their comment, a
numpy
array is a much better way to store matrices instead of lists of lists. Why? See this question
import numpy as np
matrix = [[0, 1, 10, 0, 0], [0, 0, 6, 0, 1], [0, 1, 4, 0, 0]]
maxval = np.max(matrix)
# maxval: 10
- Iterate over rows, create a list of max values in each row. Then find the max of this list
matrix = [[0, 1, 10, 0, 0], [0, 0, 6, 0, 1], [0, 1, 4, 0, 0]]
rowmax = [max(row) for row in matrix]
maxval = max(rowmax)
# or in one line:
maxval = max(max(row) for row in matrix)
- Use
map
. This is essentially the same as the previous method.
matrix = [[0, 1, 10, 0, 0], [0, 0, 6, 0, 1], [0, 1, 4, 0, 0]]
maxval = max(map(max, matrix))