+ 3
Difference between takewhile() and map() function
num = [0,1,3,6,10,15,21,28] print(list(takewhile(lambda x : x<=6 , nums))) print(list(map(lambda x : x<=6 , nums))) output is----- [0, 1, 3, 6] [True, True, True, True, False, False, False, False] and why not [0,1,3,6] why the output of map() function displays in True False... But in def add_five(x): return x+5 nums = [11,22,33,44,55] result = list(map(add_five,nums)) print(result) output --- [16, 27, 38, 49, 60] I am not getting how map() works??
3 RĂ©ponses
+ 6
takewhile() stops as soon as the first non-fitting element is found. That's 10 in your list 'num'. Even if there are more elements after 10 that meet the requirement of x <= 6, takewhile won't find them. map() iterates over the whole list and finds every element that is <= 6.
In general, map() is used to apply a function to a set or list of values. In your first example, the lambda function will return True for every number <= 6 and False for every other number. map() applies this lambda function on the list 'num'. So the result is a list of booleans.
+ 5
never seen the "takewhile" function o_O
anyway, you can use "filter" instead of "map" and it will give you [0, 1, 3, 6] (and any other value which meets the criteria unlike "takewhile" which stops once a non fitting element is encountered)
+ 2
Burey takewhile is part of itertools đ€