pirelius
pirelius

Reputation: 129

Python: Lambda function

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>

Upvotes: 4

Views: 1314

Answers (5)

kindall
kindall

Reputation: 184465

Others have covered your problems with the lambda. Now this:

<filter object at 0x102d2b6d8>

This is your result. It is not an error; it is an iterator. You have to use it as a sequence somehow. For example:

print(*filter(lambda x: len(x) > average, words))

Or if you want it as a list:

print(list(filter(lambda x: len(x) > average, words)))

Upvotes: 2

Stuart
Stuart

Reputation: 9868

In case you're wondering why there are contradictory answers being given here, note that in Python 2 you can do:

print filter(lambda x: len(x) > avg, words)

But as others have said, in Python 3 filter is an iterator and you have to iterate through its contents somehow to print them.

Upvotes: 2

heltonbiker
heltonbiker

Reputation: 27615

You need to have same variable in both sides of : operator.

lambda x:len(x) > avg

Here, x is the argument. This is equivalent to:

def aboveAverage(x):
    return len(x) > avg

only without aboveAverage function name.

Example use:

print map(lambda x:len(x) > avg, words)

Upvotes: 1

Padraic Cunningham
Padraic Cunningham

Reputation: 180550

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']

Upvotes: 3

Daniel
Daniel

Reputation: 101

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)

Upvotes: 3

Related Questions