array max

🏠

Builtin

Finding the maximum value in a list is easily done using the builtin max()

1 max([0,1,0,2,1,0,1,3,2,1,2,1]) # 0

Reduce

This is very similar to using reduce:

1 from functools import reduce
2 A = [0,1,0,2,1,0,1,3,2,1,2,1]
3 m = reduce(lambda a, x: max(a, x), A)
4 print(m)

Output:

1 0

Iterative

However, very often you'll want to do so iteratively, to use the max up until this v for example.

1 A = [0,1,1,1,2,1,0,1,3,2,1,2,1]
2 m = float('-inf')
3 for v in A:
4     m = max(v, m)
5     print(m, end=' ')

Output:

1 0 1 1 1 2 2 2 2 3 3 3 3 3

Notice the use of float('-inf') . It can feel a little counterintuitive mixing types, but this is easier to remember than sys.maxsize.

See Also

array min