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?
3 Answers 3
numpy.ndarray overloads the * operator by defining its own __mul__ method. Likewise for +, -, etc. This allows for vector arithmetic.
Comments
Its all about Overriding operators in numpy
You can learn numpy.arry here
Let us focus on your lamda function for each;
1. numpy array :
arr = numpy.array([1, 2, 3])
type(arr)
scale = lambda x: x * 3
scale(arr)
this takes each element from array
2. normal list:
a =[1,2,3]
type(a)
scale = lambda x: x * 3
scale(a)
this takes full list as x and multiplies the list here itself
Comments
These are two different objects which behaves differently when you use * operator on them.
In the first case you generate a numpy array. In this case, * operator was overloaded for performing multiplication. i.e. every element will be multiplied by 3.
In the second case you generate a list. In this case the * operator is treated as a repetition operator, and the entire list is repeated 3 times.
code example:
type(np.array([1,2,3]))
type([1, 2, 3])
result:
numpy.ndarray
list
lambda... anyway,numpyarrays override most operators to perform vectorized operations. That's one of the key features ofnumpy...