I feel surprised that abs
works on numpy array but not on lists. Why is that?
import numpy as np
abs(np.array((1,-2)))
array([1, 2])
abs([1,-1])
TypeError: bad operand type for abs(): 'list'
Also, built in functions like sum
also works on numpy array. I guess it is because numpy array supports __getitem__
? But in case of abs
, if it depends on __getitem__
it should work for list as well, but it didn't.
abs function calculates absolute values. So what does Numpy absolute value do? Put simply, Numpy absolute value calculates the absolute value of the values in a Numpy array. So let's say we have some numbers in an array, some negative and some positive.
NumPy has many built-in functions for mathematical operations and array manipulation.
As the array size increase, Numpy gets around 30 times faster than Python List. Because the Numpy array is densely packed in memory due to its homogeneous type, it also frees the memory faster.
There are several important differences between NumPy arrays and the standard Python sequences: NumPy arrays have a fixed size at creation, unlike Python lists (which can grow dynamically). Changing the size of an ndarray will create a new array and delete the original.
That's because numpy.ndarray
implements the __abs__(self)
method. Just provide it for your own class, and abs()
will magically work. For non-builtin types you can also provide this facility after-the-fact. E.g.
class A:
"A class without __abs__ defined"
def __init__(self, v):
self.v = v
def A_abs(a):
"An 'extension' method that will be added to `A`"
return abs(a.v)
# Make abs() work with an instance of A
A.__abs__ = A_abs
However, this will not work for built-in types, such as list
or dict
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With