Reputation: 142
I have an interesting question regarding the lambda function in python. I would love to hear from you a brilliant explanation.
short_list = np.array([1,2,3,4,5])
func_1 = lamda x: x*2
func_2 = lamda x: x - x.mean()
When we use func_1 on short_list, we pretty much multiply each element with 2.
And when apply func_2 on short_list, we subtract each element with the mean of the short_list.
My question is: since x in the lambda function represent each element in the list, how come python can understand x.mean() as the mean of the short_list?
Any explanation is welcomed, and thank you so much for your help!
Upvotes: 0
Views: 67
Reputation: 1075
This is because you are working with an np.array, and therefor x is a vector.
func_1 = x*2 is the same as short_list * 2. If you pass it an np.array the array is multiplied by 2. (This is not applied element wise - it is applied to the entire vector at once)
func_2 is the same as short_list - the scalar short_list.mean(). This will result in an np.array with each element - the scalar short_list.mean() again not applied element wise, but as a vector)
The bottom line is every operation is on the np.array directly and not on its elements. There is no loop.
Upvotes: 1