Anuj More
Anuj More

Reputation: 22121

Syntax error while using Lambda functions

I have a list with some dummy email address as below:

listEmails = ['[email protected]', '[email protected]', '[email protected]']

I was trying to use lambda and filter to get the list of valid email address. let's assume [email protected] is the only invalid email address.

I used the regular expression to filter out the invalid emails using the below code.

listValid = list(filter(lambda x: x if re.match(r"^[A-Za-z0-9\.\+_-]+@[A-Za-z0-9\._-]+\.[a-zA-Z]{0,3}$",x) ,listEmails))

I have been receiving a syntax error at , before listEmails)).

Generally, the lambda function takes the value after the comma(,) as the input value, so I am not sure if the lambda function is assuming x from re.match(r"^[A-Za-z0-9\.\+_-]+@[A-Za-z0-9\._-]+\.[a-zA-Z]{0,3}$",x) as the input value.

Lambda function with if conditions are possible from the below case:

from functools import reduce
f = lambda a,b: a if (a > b) else b
reduce(f, [47,11,42,102,13])

So, I wanted to know why it isn't working in my case?

Note: Since I got an error at the lambda function itself, I haven't evaluated if the list(filter( would return the desired result.

Upvotes: 3

Views: 2266

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1125398

You are missing an else clause in the conditional expression:

x if re.match(...) else None

You cannot just use the if on its own; all expressions always produce a result, so if the re.match() returns None, you need to decide what should be returned instead.

You don't need a conditional expression here at all, just return the result of the re.match() call:

listValid = list(filter(lambda x: re.match(r"^[A-Za-z0-9\.\+_-]+@[A-Za-z0-9\._-]+\.[a-zA-Z]{0,3}$", x), listEmails))

In Python 3, it is often easier to just use a list comprehension instead of filter():

listValid = [x for x in listEmails if re.match(r"^[A-Za-z0-9\.\+_-]+@[A-Za-z0-9\._-]+\.[a-zA-Z]{0,3}$", x)]

I'd store the compiled regular expression in a separate variable to make that a little more readable:

email_test = re.compile(r"^[A-Za-z0-9\.\+_-]+@[A-Za-z0-9\._-]+\.[a-zA-Z]{0,3}$")
listValid = [x for x in listEmails if email_test.match(x)]

Upvotes: 8

Caumons
Caumons

Reputation: 9595

You are missing the else part in your ternary expression.

As you stated:

a if a > b else b

Upvotes: 3

Related Questions