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.
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”.
In Python 3 the filter function returns a filter object, unlike Python 2, which returned a list. Same applies to range, map, zip and possibly others that escape me, at present.
To access the object elements, we need to cast it as a list.
I’m assuming you used it in a for loop? We can iterate over a filter object, but we cannot inspect it without using list, unless you are running Python 2.
Consider…
>>> a = filter(lambda x: x % 2, [1,2,3,4,5,6,7,8,9])
>>> a
<filter object at 0x02E68A70>
>>> for x in a:
print (x)
1
3
5
7
9
>>>