[Numpy-discussion] spurious IndexError?

Robert Kern robert.kern at gmail.com
Tue Aug 7 23:04:12 EDT 2007

john saponara wrote:
> Using numpy-1.0.2/python-2.5/winxp pro sp2:  in the following, the only 
> array is 'a', and I'm not using it as an index, so why do I get the 
> IndexError below?
> --- start python session ---
>  >>> a=array([[1,3],[2,4]])
>  >>> a
> array([[1, 3],
>         [2, 4]])
>  >>> f=lambda i,j: a[i,j]
>  >>> f(1,1)
> 4
>  >>> fromfunction(f,(2,2))
> Traceback (most recent call last):
>    File "<stdin>", line 1, in <module>
>    File "C:\Python25\Lib\site-packages\numpy\core\numeric.py", line 514, 
> in fromfunction
> 	return function(*args,**kwargs)
>    File "<stdin>", line 1, in <lambda>
> IndexError: arrays used as indices must be of integer (or boolean) type
> --- end python session ---
> The upstream maple is written in 'fromfunction' style, and I have no 
> control over that but want to port it to python in the most natural way 
> possible.
> The session suggests that lambda has no trouble with an array, so the 
> problem seems to be related to the way 'fromfunction' works.  What am I 
> missing?

fromfunction() takes the (2, 2) and forms arrays of indices. It then calls your
function with those arrays as arguments. It does not loop. The default dtype of
these arrays is float, not int. You must use "dtype=int" in your call to

def fromfunction(function, shape, **kwargs):
    """Returns an array constructed by calling a function on a tuple of number

    The function should accept as many arguments as the length of shape and
    work on array inputs.  The shape argument is a sequence of numbers
    indicating the length of the desired output for each axis.

    The function can also accept keyword arguments (except dtype), which will
    be passed through fromfunction to the function itself.  The dtype argument
    (default float) determines the data-type of the index grid passed to the

Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

More information about the NumPy-Discussion mailing list