While familiarizing myself with numpy
, I noticed an interesting behaviour in numpy
arrays:
import numpy as np
arr = np.array([1, 2, 3])
scale = lambda x: x * 3
scale(arr) # Gives array([3, 6, 9])
Contrast this with normal Python lists:
arr = [1, 2, 3]
scale = lambda x: x * 3
scale(arr) # Gives [1, 2, 3, 1, 2, 3, 1, 2, 3]
I'm curious as to how this is possible. Does a numpy
array override the multiplication operator or something?
We can map a function over a NumPy array just by passing the array to the function.
A Python lambda function behaves like a normal function in regard to arguments. Therefore, a lambda parameter can be initialized with a default value: the parameter n takes the outer n as a default value. The Python lambda function could have been written as lambda x=n: print(x) and have the same result.
In general, SymPy functions do not work with objects from other libraries, such as NumPy arrays, and functions from numeric libraries like NumPy or mpmath do not work on SymPy expressions.
numpy.ndarray
overloads the *
operator by defining its own __mul__
method. Likewise for +
, -
, etc. This allows for vector arithmetic.
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