I'm relatively new to Lambda functions and esp this one got me quite confused. I have a set of words that have an average length 3.4 and list of words = ['hello', 'my', 'name', 'is', 'lisa']
I want to compare the length of a word to average length and print out only the words higher than average length
average = 3.4
words = ['hello', 'my', 'name', 'is', 'lisa']
print(filter(lambda x: len(words) > avg, words))
so in this case i want
['hello', 'name', 'lisa']
but instead I'm getting:
<filter object at 0x102d2b6d8>
list(filter(lambda x: len(x) > avg, words)))
filter is an iterator in python 3. You need to iterate over or call list on the filter object.
In [17]: print(filter(lambda x: len(x) > avg, words))
<filter object at 0x7f3177246710>
In [18]: print(list(filter(lambda x: len(x) > avg, words)))
['hello', 'name', 'lisa']
lambda x: some code
Means that x is the variable your function gets
so basically you need to replace words with x and change avg to average because there isn't a variable called avg in your namespace
print filter(lambda x: len(x) > average, words)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With