how to print the letter if it exists in the list using lambda,filter function

355 views Asked by At
letters = ['a', 'b', 'c', 'd', 'e', 'f']
list(filter(lambda x : print(x) if 'e' in x ,letters))
SyntaxError: invalid syntax
1

There are 1 answers

1
Siddharth Asodariya On

you are getting this "invalid syntax" error because you are applying filter for list letters. For x=="e" or "e" in x you are returning item of list as it is but for other value you have to return something.

You can add else condition like below:

letters = ['a', 'b', 'c', 'd', 'e', 'f']
list(filter((lambda x : x if 'e'==x else None),letters))

Output:

['e']

if you use jupyter you will get this as output otherwise you have to print that list.

For printing directly you can do this:

letters = ['a', 'b', 'c', 'd', 'e', 'f']
d = list(filter((lambda x : print(x) if 'e'==x else None),letters))

Output:

e

I hope I understood your question properly.

Other reference for printing in lambda Python documentation, Why doesn't print work in a lambda?

Conclusion: "Add else condition for if 'e' not in x"