Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python sum() has a different result after importing numpy

Tags:

python

numpy

sum

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

like image 558
aamir23 Avatar asked Dec 03 '22 23:12

aamir23


1 Answers

"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.

like image 70
Warren Weckesser Avatar answered Dec 25 '22 13:12

Warren Weckesser