2

Let say I have a list called "y_pred", I want to write a lambda function to change the value to 0 if the value is less than 0.

Before: y_pred=[1,2,3,-1]

After: y_pred=[1,2,3,0]

I wrote something like this, and return an error message

y_pred=list(lambda x: 0 if y_pred[x]<0 else y_pred[x])    
TypeError: 'function' object is not iterable
1
  • 3
    You can use list comprehension for this y_pred=[i if i >= 0 else 0 for i in y_pred] Commented Apr 28, 2022 at 6:56

3 Answers 3

7

You want an expression (a if cond else b) mapped over your list:

y_pred_before = [1, 2, 3, -1]
y_pred_after = list(map(lambda x: 0 if x < 0 else x, y_pred_before))
# => [1, 2, 3, 0]

A shorter form of the same thing is a list comprehension ([expr for item in iterable]):

y_pred_after = [0 if x < 0 else x for x in y_pred_before]

Your error "TypeError: 'function' object is not iterable" comes from the fact that list() tries to iterate over its argument. You've given it a lambda, i.e. a function. And functions are not iterable.

You meant to iterate over the results of the function. That's what map() does.

Sign up to request clarification or add additional context in comments.

3 Comments

Even simpler: [max(0, y) for y in y_pred]
@flakes True, but this was not meant to be code golf. :) I wanted to keep the OP's ternary.
Just pointing it out! I did +1 the answer!
0

You can use numpy (assuming that using lambda is not a requirement):

import numpy as np
y_pred = np.array(y_pred)
y_pred[y_pred < 0] = 0
y_pred

Output:

array([1, 2, 3, 0])

Comments

0

An easy way to do this with list comprehension:

y_pred=[x if x>0 else 0 for x in y_pred_before] 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.