Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why built-in functions like abs works on numpy array?

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.

like image 579
colinfang Avatar asked Jan 06 '14 15:01

colinfang


People also ask

What is abs function in NumPy?

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.

Is NumPy a built in function?

NumPy has many built-in functions for mathematical operations and array manipulation.

Why do NumPy array operations have better performance compared to Python functions and loops?

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.

What's the difference between Python built in array and NumPy array?

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.


1 Answers

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.

like image 91
Michael Wild Avatar answered Oct 11 '22 19:10

Michael Wild