Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

163
Views
Lambda with if statement

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
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report

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])
over 4 years ago · Santiago Trujillo Report

0

An easy way to do this with list comprehension:

y_pred=[x if x>0 else 0 for x in y_pred_before] 
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!