How do I filter out the letter in the set of words with lambda function?
For example:
I have to filter out every word containing letter "K".
["rabbit", "chuck", "Joe", "war", "rock", "docker"]
["chuck", "rock", "docker"]
I was told to provide the efforts:
list = ["rabbit", "chuck", "Joe", "war", "rock", "docker"]
print(list)
listfilter = list(filter(lambda x: (x == 'k'), lst))
print(listfilter)
>Solution :
There are two issues with your code:
- The
listvariable name shadows thelist()builtin — pick a different name for your original list instead. - Your lambda function isn’t correct. Instead of
lambda x: x == k, it should belambda x: 'k' not in x.
data = ["rabbit", "chuck", "Joe", "war", "rock", "docker"]
listfilter = list(filter(lambda x: ('k' not in x), data))
# Prints ['rabbit', 'Joe', 'war']
print(listfilter)