trojek - 8 months ago 41

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?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

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

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**