Reputation: 29
i have a list:
seq = ['soup','dog','salad','cat','great']
As per the definition of filter, below code fetches the correct result:
list(filter(lambda w: w[0]=='s',seq))
['soup','salad']
i.e returning the list containing only words starting with 's'
but if i am using map function, it is returning the list as true/false:
list(map(lambda w: w[0]=='s',seq))`
[True, False, True, False, False]
please explain the map function w.r.t. to the above example
Upvotes: 1
Views: 82
Reputation: 51683
map
applies a function to a sequence and returns a generator.
Example:
k = list(map(int,["1","2","3"]))
int()
is a function string->int
hence k
becomes:
k == [1,2,3] # (a list of ints)
Your lambda is a fuction string->bool
that takes a string
and evaluates the first char to be 's'
or not:
lambda w: w[0]=='s'
As a function of string->bool
, your result is a list
of bool
s when using list(map(lambda w: w[0]=='s', seq))
to apply your lambda to your sequence.
Btw. you could also have done it as list comprehension:
s_seq = [x for x in seq if x[0]=='s'] # which is closer to what filter does...
This might shed more light on map()
: Understanding the map function
Upvotes: 2