Lambda syntax


#1



https://www.codecademy.com/courses/python-beginner-en-KAgt5/3/2?curriculum_id=4f89dab3d788890003000096


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)


#2

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


#3

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


#4

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


#5

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

Lets understand this...

filter(),list and lambda..

filter(function,list)
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)...so it returns True and so filter returns the whole list again.

this code...

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

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


#6

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.


#7

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?


#8

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


#9

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


#10

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