I came across this problem by Jake VanderPlas and I am not sure if my understanding of why the result differs after importing the numpy module is entirely correct.
>>print(sum(range(5),-1)
>> 9
>> from numpy import *
>> print(sum(range(5),-1))
>> 10
It seems like in the first scenario the sum function calculates the sum over the iterable and then subtracts the second args value from the sum.
In the second scenario, after importing numpy, the behavior of the function seems to have modified as the second arg is used to specify the axis along which the sum should be performed.
Exercise number (24) Source - http://www.labri.fr/perso/nrougier/teaching/numpy.100/index.html
"the behavior of the function seems to have modified as the second arg is used to specify the axis along which the sum should be performed."
You have basically answered your own question!
It is not technically correct to say that the behavior of the function has been modified. from numpy import *
results in "shadowing" the builtin sum
function with the numpy sum
function, so when you use the name sum
, Python finds the numpy version instead of the builtin version (see @godaygo's answer for more details). These are different functions, with different arguments. It is generally a bad idea to use from somelib import *
, for exactly this reason. Instead, use import numpy as np
, and then use np.sum
when you want the numpy function, and plain sum
when you want the Python builtin function.
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