Why is there difference between cmd line and .py file?

Thomas 'PointedEars' Lahn PointedEars at web.de
Tue Jan 5 18:21:44 EST 2016


Joel Goldstick wrote:

> On Tue, Jan 5, 2016 at 3:45 PM, Robert <rxjwg98 at gmail.com> wrote:
>> import numpy as np
>>
>> In [154]: np.sum(expectation_A)[0]
>> […]
>> IndexError: invalid index to scalar variable.
> 
> I've not used numpy, but you should print expectation_A to see what's in
> it.  It may be empty, causing the index.

Did you mean “IndexError” instead of “index”?

> It may be that expectation_A is an integer, not a list

Please think about this again.

| $ python3
| Python 3.4.4 (default, Dec 21 2015, 09:19:42)
| [GCC 5.3.1 20151219] on linux
| Type "help", "copyright", "credits" or "license" for more information.
| >>> import numpy
| >>> print(numpy.sum.__doc__)
| 
| Sum of array elements over a given axis.

The problem is instead that np.sum(…) *returns* a scalar value (as expected 
from a summation method when passed only scalar values) and _not_ a list 
(insofar the error message is misleading; there is no scalar *variable* 
causing the problem, but a scalar return *value*):

|     Parameters
|     ----------
|     a : array_like
|         Elements to sum.
| […]
| 
|     Returns
|     -------
|     sum_along_axis : ndarray
|         An array with the same shape as `a`, with the specified
|         axis removed.   If `a` is a 0-d array, or if `axis` is None, a 
|         scalar is returned.  If an output array is specified, a reference
|         to `out` is returned.
| 
| […]
| 
|     Examples
|     --------
|     >>> np.sum([0.5, 1.5])
|     2.0
| 
`----

So you cannot use the index notation with the *return* value.  Try e.g. 
42[0]; it does not work because it does not make sense.

It is more likely that the index notation was misplaced: 

np.sum(expectation_A[0])

would make sense if the first element of the iterable referred to by 
“expectation_A” were a numeric scalar or a reference to a list.


Please trim your quotes to the relevant minimum.

-- 
PointedEars

Twitter: @PointedEars2
Please do not cc me. / Bitte keine Kopien per E-Mail.



More information about the Python-list mailing list