2

Python question:

print(sum(range(5),-1)) 
from numpy import * 
print(sum(range(5),-1))

9
10

What is logical behind it? Thank you

4
  • Numpy must be redefining range, and it has different boundry rules. Commented Mar 22, 2017 at 14:59
  • 1
    The first line is equivalent to 0+1+2+3+4+(-1). The third line is equivalent to 0+1+2+3+4 on axis=-1. Use import numpy as np and then rewrite the third line as np.sum(range(5),-1). And read the documentation for np.sum() Commented Mar 22, 2017 at 14:59
  • Numpy does not redefine range. The second argument in np.sum() is axis. It will only sum the items in the first argument. Commented Mar 22, 2017 at 15:00
  • Ahh, my bad. Shot in the dark. I didn't think a summing function could have different behavior. Commented Mar 22, 2017 at 15:01

1 Answer 1

4

numpy.sum() signature is as follows (with some arguments omitted):

numpy.sum(a, axis=None, dtype=None, out=None, ...)

Python's sum signature:

sum(iterable, start=0)

sum iterates over supplied iterable, sums the values, and then adds -1 (i.e. substracts 1). numpy.sum just sums all the values from supplied iterable, and receives an axis parameter as 1, which in your case doesn't change the behaviour.

Sign up to request clarification or add additional context in comments.

1 Comment

It's not so important, but sum doesn't add the start value at the end of the operation - it rather starts with the start value which defaults to 0, and adds the sequence to it. Like in CPython here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.