Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

trying to understand lambda

Tags:

python

When I do

dict = {'Alice': '7898', 'Beth': '9102', 'Cecil': '3258'}
print filter(lambda x: x, dict['Alice'])

it shows: 7898

When I do the next

dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
print filter(lambda x: x=="2341", dict['Alice'])

it shows:

Why it doesn't show True. How to get True ?

like image 273
ouea Avatar asked Dec 13 '22 12:12

ouea


2 Answers

filter() does the following: given a function and an iterable (like a list, tuple, etc), passes each item in the list to a function. For each item, the function returns a boolean true or false. If the function returns true on an item, the item is added to a new list.

When filter is finished, it returns the new list with all of the selected items. This allows you to "filter" through a list based on a criteria and select only the items matching the criteria.

A tricky thing is happening here. filter() loops through any iterable. This includes a string. When you pass dict['Alice'] as the object to iterate, it's passing '2341', and running the filter on each character in the string. You could break the filter's logic down as follows:

def matches(x):
    return x == '2341'

result = ''
for char in x:
    if matches(char):
         result += char

print result

This doesn't work, because none of your individual characters equal '2341'.

like image 135
lunixbochs Avatar answered Jan 04 '23 20:01

lunixbochs


It looks like your misunderstanding is with filter, to me. You pass a predicate function and an iterable object to filter. It creates a new object containing those items from the first iterable for which the predicate returns a true value (not necessarily True itself, just something that tests as true). The iterable in the two cases is the string '2341', which means the individual letters are tested. Of course the string '2341' is not equal to any of '2', '3', '4', or '1'.

Try it with a tuple and it's easier to see what's going on:

>>> tup = tuple(dict['Alice'])
>>> tup
('7', '8', '9', '8')
>>> filter(lambda x: x, tup)
('7', '8', '9', '8')
>>> tup
('7', '8', '9', '8')
>>> filter(lambda x: x, tup)
('7', '8', '9', '8')
>>> filter(lambda x: x=="2341", tup)
()
like image 43
Michael J. Barber Avatar answered Jan 04 '23 18:01

Michael J. Barber