pythonpython-3.xmaxabsolute-value

Pythonic way to find maximum absolute value of list


Given the following:

lst = [3, 7, -10]

I want to find the maximum value according to absolute values. For the above list it will be 10 (abs(-10) = 10).

I can do it as follows:

max_abs_value = lst[0]
for num in lst:
    if abs(num) > max_abs_value:
        max_abs_value = abs(num)

What are better ways of solving this problem?


Solution

  • The built-in max takes a key function, you can pass that as abs:

    >>> max([3, 7, -10], key=abs)
    -10
    

    You can call abs again on the result to normalise the result:

    >>> abs(max([3, 7, -10], key=abs))
    10