Home > database >  Fastest way to calculate absolute values of a list
Fastest way to calculate absolute values of a list

Time:05-23

I have a question about calculating the absolute value of a list. I have written a short code to calculate the absolute value of each single element from a list and I was wondering if there is a faster way of doing this, Thanks!

test_list = [5, -60, 74, -83, -120]
result =  [abs(i) for i in test_list]
print(result)

CodePudding user response:

The numpy package is a package for doing fast maths operations in Python. It is so fast because it itself is not actually written in Python (which is a very slow language), but instead in C (which is very fast), and it is very optimised.

After installing numpy:

pip install numpy

This code can be rewritten as:

import numpy as np

test_list = np.array([5, -60, 74, -83, -120])
result = np.abs(test_list)
print(result)

It will work much faster this way with larger arrays, although bear in mind that for small arrays (like this example), it is not worth it as numpy takes a while to import.

CodePudding user response:

You could try map:

test_list = [random.randint(-10,10) for _ in range(1_000_000)]
%timeit result =  [abs(i) for i in test_list]
189 ms ± 11.4 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
%timeit res = np.abs(test_list)
148 ms ± 9.44 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
%timeit res = list(map(abs, test_list))
77.2 ms ± 1.35 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
  • Related