Lambda syntax


Oops, try again. Your syntax doesn't look quite right. Take a look at the examples in the instructional text and the Hint if you need help!

sthg is wrong in my code??

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


Inside this code you need to change one thing.!
lambda generalListVariable : generalListVariable


now I know the answer thanks
languages = ["HTML", "JavaScript", "Python", "Ruby"]
print filter(lambda x: x == "Python", languages)


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

can't i filter the index like this?
or maybe use x[::2]?
i should straight away print python
but instead it takes HTML as a string and processes HTM


filter(lambda x: x[2], languages)

Lets understand this...

filter(),list and lambda..

Every time it (list) hands over one item to function and if function checks if it satisfies the condition or not.

lambda variable : condition

If it satisfies then It will put item into list again otherwise it will be excluded from the list.

As your lambda function's condition gives a single character each time ,a single character string(which is Truthy value) it returns True and so filter returns the whole list again.

this code...

def f(x):
    if x[2]:
        return True
        return False
print filter(f,languages)

is same as...
print filter(lambda x: x[2], languages)


What i thought that if i use x[2] it would mean that the list will be checked for index 2 and python being at index 2 will be printed but it is returning one character at a time and is going through the elements rather than the list.


As I explained function checks items of list against the condition.
If list item satisfies the condition of function, It will return True and when filter() sees the True,It will let item remain in the list otherwise it will be excluded!
Have your problem solved?


That means I'll have to check for language [x] == python
But i think simple x== python will also do?


why language[x] ,As I said the variable (x or anything you will use as general variable of lambda) will 'take' value of every item of list and test the lambda condition and returns True/False. the values(item of list) on which we get True will remain in list otherwise they'll be excluded from list.

Back to instruction...

Instruction simply says if you see 'Python' string in the list then return it and exclude every item which is not 'Python' from the list!
(using lambda andfilter() )


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