hatmatrix
hatmatrix

Reputation: 44952

Where does numpy.ndarray's iterable behavior come from?

numpy's ndarray class is defined as

class ndarray(__builtin__.objects)

From what I can gather, __builtin__.objects is not an iterable type? For this reason I find this behavior surprising:

Arr = numpy.array('As Far As I Know'.split())
=> array(['As', 'Far', 'As', 'I', 'Know'], dtype='|S4')
print map(lambda x: x[0],Arr)
=> ['A', 'F', 'A', 'I', 'K']

Or does this come from the attributes of the (list) object that is passed to the __init__ method of the ndarray? But then why cannot I not use methods like list.reverse on the array object, if it is internally stored as a list?

(and as a side not does anyone know any better way to apply string-operations on each element of ndarray objects?)

Upvotes: 2

Views: 1791

Answers (1)

Sven Marnach
Sven Marnach

Reputation: 602435

numpy.ndarray defines __iter__(), which the usual (and only) mechanism to make instances of a type iterable. Note that numpy.ndarray is a C extension type, but this doesn't matter for the question why it is iterable. Both, types you define in Python and C extension types can be made iterable by defining __iter__().

Upvotes: 7

Related Questions