Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading