How can I write a lambda to check for a particular word in a list?


#1

Question

How can I write a lambda to check for a particular word in a list?

Answer

If we’re given some list of strings, like languages = ["HTML", "JavaScript", "Python", "Ruby"], we’d write a lambda where each value checked is each item in the list.
From the example below, we see x being used as each number in a range() of numbers.

my_list = range(16)
filter(lambda x: x % 3 == 0, my_list)

What we want to do here is very similar, in that our x, or whatever you want to call it, will become each item in a list. The only difference is that our x is going to be each word in the list. And instead of checking if x is evenly divisible by 3, we need to check if it’s equivalent to ”Python”.


FAQ: Learn Python - Advanced Topics in Python - Lambda Syntax
#2

While a lambda can do this job very easily, it may be more tool than is needed in the particular situation.

print ("Python" in languages)        # True
print (languages.index('Python'))    # 2

Where the tool may be more effective is if we were looking for all the words that are not ‘Python’, or that come before/after it in the alphabet, etc.

print (list(filter(lambda x: x != 'Python', languages)))
# ['HTML', 'JavaScript', 'Ruby']

However, this again may be more than we need since a list comprehension can do the same thing…

print ([x for x in languages if x != 'Python'])
# ['HTML', 'JavaScript', 'Ruby']

That’s the beauty of the language… More than one way to cook an egg.