Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Lambda function

Tags:

python

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>
like image 707
pirelius Avatar asked Dec 19 '22 09:12

pirelius


2 Answers

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']
like image 73
Padraic Cunningham Avatar answered Jan 28 '23 16:01

Padraic Cunningham


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)
like image 36
Daniel Avatar answered Jan 28 '23 16:01

Daniel