Kyrellos Rezk
Kyrellos Rezk

Reputation: 27

filter using lambda with if condition

friends_filter = ["Osama", "Wessam", "Amal", "Essam", "Gamal", "Othman"]
namess = filter(lambda names: names if names[-1].lower() == 'm', friends_filter)
for name in namess:
    print(name)

why it gives me error (syntax error) before list name

Upvotes: 1

Views: 240

Answers (2)

alparslan mimaroğlu
alparslan mimaroğlu

Reputation: 1490

You have a Syntax error because you need an else statement for your inline if. but you don't have to use an inline if in your lambda expression if names[-1].lower() == 'm' else None

Upvotes: 2

Alireza
Alireza

Reputation: 2123

The predicate only has to return the result of the comparison, not the value itself.

friends_filter = ["Osama", "Wessam", "Amal", "Essam", "Gamal", "Othman"]
namess = filter(lambda names: names[-1].lower() == 'm', friends_filter)
for name in namess:
    print(name)

Upvotes: 2

Related Questions