Syntax error when using lambda functions
I have a list with a bogus email address as shown below:
listEmails = ['brian-23@email.com', 'britts_54@email.com', 'lara$@email.com']
I tried to use lambda
and filter
to get a list of valid email address. let's say that lara$@email.com
is the only invalid email address.
I have used regex to filter out invalid emails using the code below.
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 got a syntax error in ,
before listEmails))
.
Typically, a function lambda
takes a value after the decimal point ( ,
) as an input valueso I'm not sure what the function is lambda
taking x
from re.match(r"^[A-Za-z0-9\.\+_-]+@[A-Za-z0-9\._-]+\.[a-zA-Z]{0,3}$",x)
as input.
In the following case, lambda functions are possible with if
:
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 is it not working in my case?
Note. Since I got the error in the function itself lambda
, I didn't evaluate if the result would return the list(filter(
desired result.
source to share
The conditional expression is missing a sentence else
:
x if re.match(...) else None
You can't just use it if
yourself; all expressions always result in a result, so if it does re.match()
return None
, you need to decide what to return.
No conditional is required here at all, just return the result of the call re.match()
:
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 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 would store the compiled regex in a separate variable to make it 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)]
source to share