1

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

1 Answer 1

2

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 bools 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

Sign up to request clarification or add additional context in comments.

1 Comment

Great answer. Something I didn't know but is very much worth noting. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.