4

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>
0

5 Answers 5

3
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']
Sign up to request clarification or add additional context in comments.

Comments

3
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)

Comments

2

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.

Comments

2

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)))

2 Comments

but this will not return a list
print won't return anything anyway. But if you want it as a list, just pass it to list(). I've added that example.
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.