trojek - 5 months ago 23

Python Question

`lst = [3, 7, -10]`

I want to find the maximum value of absolute value. 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?

Answer Source

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
```