Home > database >  How to use lambda in iterating list with if statement?
How to use lambda in iterating list with if statement?

Time:11-06

I have this working for loop, I want to use lambda that prints same results below

val = [20,30,26,38,40,22,35]
list1=[]
for i in val:
    if i > 29:
        list1.append(i)
print("list1",list1) 
#output list1 [30, 38, 40, 35]

CodePudding user response:

You can create lambda function to compare the value and return boolean, and call this function in your if condition. It's not a recommended way though E731 do not assign a lambda expression, use a def:

list1=[]
get_flag = lambda i:i>29
for i in val:
    if get_flag(i):
        list1.append(i)
print(list1)
[30, 38, 40, 35]

Or, you can just use filter builtin and pass a lambda function. It's equivalent List Comprehension is already there in another answer.

list(filter(lambda i: i>29, val))
[30, 38, 40, 35]

CodePudding user response:

Do you want to use lambda function, Then it will be,

val = [20,30,26,38,40,22,35]
fun = lambda val: [v for v in val if v>29]
res = fun(val)
# [30, 38, 40, 35]

CodePudding user response:

Not sure why lambdas, but I think you might be referring to something like this:

filtered = [x for x in val if x > 29]

This seems to be the most code-efficient way to achieve what you're asking.

  • Related