Why I can pass an array as input to a lambda function that uses numpy but I cant pass it to a lambda function without numpy?

Starting from these two lambda functions

import numpy as np

relu = (lambda x: np.maximum(0, x),
        lambda x: 1 if x > 0 else 0)

Obviously the two functions work correctly when I pass a single number, but when I pass an array/list relu[0] works but not relu[1].

a = [1, 2, 3, 4]
print(relu[0](a))  # this one works
print(relu[1](a))  # not works
print([relu[1](v) for v in a])  # also works

>Solution :

Many numpy functions, e.g. maximum, accept array-like argument, i.e. types that can be converted to numpy arrays, and numpy coverts them to numpy arrays automatically.

a = [1, 2, 3, 4]
print(relu[0](a))  # a is converted from list to numpy array

Your second example raises a TypeError

TypeError: '>' not supported between instances of 'list' and 'int'

because you can’t compare a list and an integer.

print(relu[1](a))  # compare a list to an integer: Fail
print([relu[1](v) for v in a])  # compare an integer to an integer: OK

Leave a Reply