-1

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

ids= [1,2,3,4,5,6,7]
val = [20,30,26,38,40,22,35]
list1=[]
for i,num  in enumerate(val):
  if num > 29:
  list1.append(ids[i])
print("ids",list1)

#output ids [2, 4, 5, 7]

The code below throws and invalid syntax. I just want to get the element value not the index.

new_id=list(filter(lambda ids[i]:   
val[i]>29, range(len(val))))
zvone
  • 18,045
  • 3
  • 49
  • 77
Glenn_ford7
  • 41
  • 1
  • 8

3 Answers3

1

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]

For updated question, to get the index, just iterate a range and filter out based on the values at given index:

>>> list(filter(lambda i: val[i]>29, range(len(val))))
[1, 3, 4, 6]
ThePyGuy
  • 17,779
  • 5
  • 18
  • 45
0

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]
Deepak Tripathi
  • 3,175
  • 1
  • 8
  • 21
0

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.

fholl124
  • 11
  • 2