1

Hi I want to implement a lambda function in python which gives me back x if x> 1 and 0 otherhwise (relu):

so I have smth. like:

p = [-1,0,2,4,-3,1]

relu_vals = lambda x: x if x>0 else 0 

print(relu_vals(p))

It is important to note that I want to pass the value of lambda to a function

but it fails....

2Obe
  • 3,570
  • 6
  • 30
  • 54

2 Answers2

3

You want to use map to apply this function on every element of the list

list(map(relu_vals, p))

gives you

[0, 0, 2, 4, 0, 1]

Also it's better to define the lambda function within map if you are not planning to use it again

print(list(map(lambda x: x if x > 0 else 0, p)))
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
  • But I want to pass the value to a variable like: relu_vals = lambda... This fails... – 2Obe Jul 05 '19 at 14:58
2

You program is right, but need some modification.

Try this,

>>> p = [-1,0,2,4,-3,1]     
>>> relu_vals = lambda x: x if x>0 else 0     
>>> [relu_vals(i) for i in p] 
[0, 0, 2, 4, 0, 1]
shaik moeed
  • 5,300
  • 1
  • 18
  • 54