Home > Software engineering >  Trying to filter with a lambda function inside of a list comprehension
Trying to filter with a lambda function inside of a list comprehension

Time:09-27

I am trying to remove all even indices from a list with a list comprehension. I am using a lambda function to filter the even indices, why is it not working?

Input:

data = [e for i, e in enumerate(raw_data) if lambda i: True if i % 2 != 0 else False]

Output:

Input In [90]
data = [e for i, e in enumerate(raw_data) if lambda i: True if i % 2 != 0]
                                             ^
SyntaxError: invalid syntax

The output is returning a syntax error where I defined by lambda. Is it not possible to use a lambda in a list comprehension as the filter argument?

EDIT 1: I know there's no reason to use lambda when I can just put the condition directly into the list comprehension, I'm just curious as to why it didn't work.

EDIT 2: Removed useless numpy code surrounding list comprehension

EDIT 3: Removed return statements from lambda

CodePudding user response:

result = [i for i in range(10) if (lambda i: i%2 == 0)(i)]

Since lambda is an anonymous function, it is still a function. You need to pass value to lambda.

  • Related