-2

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)

1 Answers1

2

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.

Lecdi
  • 2,189
  • 2
  • 6
  • 20
  • 1
    @Mark True, I will edit my question to specify that this is only true for larger arrays, but this is probably what the OP meant anyway. – Lecdi May 22 '22 at 19:58