trojek
trojek

Reputation: 3228

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?

Upvotes: 20

Views: 61485

Answers (5)

blackcat
blackcat

Reputation: 78

In case someone wants to preserve the +- sign (not all use case has negative elements)

def max_magnitude(numbers):
 max_num = numbers[0]
 max_abs = abs(max_num)

 for num in numbers[1:]:
     abs_num = abs(num)
     if abs_num > max_abs or (abs_num == max_abs and num > max_num):
        max_num = num
        max_abs = abs_num
    elif abs_num == max_abs and num == 0 and math.copysign(1, num) > math.copysign(1, max_num):
        max_num = num
 return max_num

Upvotes: 0

Chris
Chris

Reputation: 22963

You can use max() with a generator comprehension:

>>> max(abs(n) for n in [3, 7, -10])
10

Upvotes: 5

B. M.
B. M.

Reputation: 18658

max(max(a),-min(a))

It's the fastest for now, since no intermediate list is created (for 100 000 values):

In [200]: %timeit max(max(a),-min(a))
100 loops, best of 3: 8.82 ms per loop

In [201]: %timeit abs(max(a,key=abs))
100 loops, best of 3: 13.8 ms per loop

In [202]: %timeit max(map(abs,a))
100 loops, best of 3: 13.2 ms per loop

In [203]: %timeit max(abs(n) for n in a)
10 loops, best of 3: 19.9 ms per loop

In [204]: %timeit np.abs(a).max()
100 loops, best of 3: 11.4 ms per loop

Upvotes: 13

idjaw
idjaw

Reputation: 26580

Use map, and just pass abs as your function, then call max on that:

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

Upvotes: 7

Moses Koledoye
Moses Koledoye

Reputation: 78554

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

Upvotes: 82

Related Questions