chen_767
chen_767

Reputation: 365

How does ndarray work with a simple function, like x**2?

How does ndarray work with a simple function, like x**2? I get this error:

arr = array([3,4,5])
f = lambda x: x**2
print f(arr)     # works, but how?
print f(3)       # works
print f([3,4,5]) # will not work
#TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'
print f((3,4,5)) # will not work
#TypeError: unsupported operand type(s) for ** or pow(): 'tuple' and 'int'

>>>f(arr)
#[ 9 16 25]
>>>f(3)
#9

finally...

class Info(object):
    def __init__(self,x):
        self.a = x<
    def __pow__(self,x):
        for i in xrange(len(self.a)):
            self.a[i]**=x
        return self

a = Info([3,4])
f = lambda x:x**2
a = f(a)
print a.a
[9, 16]

Upvotes: 2

Views: 169

Answers (1)

wim
wim

Reputation: 363304

Because ndarray defines the behaviour for ** operator, whereas lists an tuples don't (they may contain whatever objects, whereas ndarrays are typically for numbers).

Upvotes: 5

Related Questions