Pythonic way to find maximum absolute value of list
Question:
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?
Answers:
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
Use map
, and just pass abs
as your function, then call max on that:
>>> max(map(abs, [3, 7, -10]))
10
You can use max()
with a generator comprehension:
>>> max(abs(n) for n in [3, 7, -10])
10
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
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?
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
Use map
, and just pass abs
as your function, then call max on that:
>>> max(map(abs, [3, 7, -10]))
10
You can use max()
with a generator comprehension:
>>> max(abs(n) for n in [3, 7, -10])
10
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