[Numpy-discussion] typecasting of single values form an array: Bug or feature?

Chris Barker chrishbarker at home.net
Thu Jul 19 19:28:14 CDT 2001

Hi all,

I am using a 2-d array to store values that will be an index into a
list. It is huge, sot to samve space I have used a type Int16. Now when
I pull a value outl it is of type array, so it can not be used to index
a sequence. The strange thing is that it works if the array is of rank
1. Some tests:

>>> from Numeric import *
>>> l = range(10) # a test list
>>> a = arange(10) # an array if Ints
>>> print type(a[3])
<type 'int'>
#So this is an Int

>>> print l[a[3]]
# and it can be used as an index.

>>> a.shape = (2,5)
#reshape it to be rank-2

>>> print type(a[1,3])
<type 'int'>
# still and Int
>>> print l[a[1,3]]
# and still usable as an index.

# now change the type
>>> a = a.astype(Int16)
>>> a.shape = (10,)
>>> print type(a[3])
<type 'int'>
#it's an Int

>>> a.shape = (2,5)
# now change the shape to rank-2

>>> print type(a[1,3])
<type 'array'>

# Now a single item is of type 'array'

>>> print l[a[1,3]]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: sequence index must be integer

# and it can not be used as an index!

I can work around this with an explicite type cast with int(), but it
seems like wierd behaviour to me. I am accesing a single item, it is
typcaste as an Int when the item is pulled out of a rank-1 array, but it
is a rank-0 array when pulled from a rank > 1 array.

Any ideas what causes this? Is there a good reson for htis, or is it a


Christopher Barker,
ChrisHBarker at home.net                 ---           ---           ---
http://members.home.net/barkerlohmann ---@@       -----@@       -----@@
                                   ------@@@     ------@@@     ------@@@
Oil Spill Modeling                ------   @    ------   @   ------   @
Water Resources Engineering       -------      ---------     --------    
Coastal and Fluvial Hydrodynamics --------------------------------------

More information about the Numpy-discussion mailing list