Lambda Syntax


languages = ["HTML", "JavaScript", "Python", "Ruby"]
print filter(lambda x: x[2], languages)

why doesn't this work?

gives the error
Oops, try again. It looks like your filter() didn't print ['Python'] to the console.


If you read instruction properly they are asking to loop over languages list and compare if any list element is "Python" , If it is "Python", then print it (in a list)! [using lambda and filter]


numx = [1,2,3,4,5]
I have to find if any element is 2 or not.

I use lambda like this..

lambda x: x == 2

Now we have to filter it..
in filter we need to do two things, lambda expression and sequence(list) which gets filtered


print filter(lambda x: x == 2, numx)
It will return a list containing 2 > [2]

do reply !


Sorry I should've presented my question correctly?
what I wanted to ask was:

for the list y

y = ['a','b','c']

def fun(x):
return x[2]

print fun(y) will give 'c'

shouldn't it be the same with lambda

print filter(lambda x: x[2], y)

should be 'c' right?


Nope, It returns list type not int type or any other type of data list includes.
What I said? Its filters the list not "it returns that value!right?"


Nice collection of reads (Articles) that'd help you tackle advance section of Python here!


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.