user2988577
user2988577

Reputation: 4207

Unexpected behaviour of np.sum which acts as np.ravel

I have a list of list of numbers and I want to sum all the numbers (regardless the list of lists). This should be a piece of cake for np.sum In fact if we have

a=[[1,2],[3,4]]
np.sum(a)

returns 10

By the way if we have

a=[[1,2],[3,4,5]]
np.sum(a)

returns

[1,2,3,4,5]

It seems quite weird to me...

Upvotes: 0

Views: 117

Answers (1)

ebarr
ebarr

Reputation: 7842

So I would hazard to guess that the answer here is pretty simple.

np.sum will evaluate the two lists and realise that it can't store their values in a normal array. It will therefore make an object array:

In [99]: x = [[1,2],[3,4,5]]

In [100]: np.array(x)
Out[100]: array([[1, 2], [3, 4, 5]], dtype=object)

When it comes to sum the elements of the array it will use the objects __add__ operator.

The addition of the two objects is:

In [103]: [1,2] + [3,4,5]
Out[103]: [1, 2, 3, 4, 5]

Therefore:

In [104]: np.sum([[1,2],[3,4,5]])
Out[104]: [1, 2, 3, 4, 5]

Upvotes: 4

Related Questions