what is the difference between itertools takewhile method and filter.they exaclty function as same so why there are two of them in python | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

what is the difference between itertools takewhile method and filter.they exaclty function as same so why there are two of them in python

difference between these functions

9th Jul 2016, 9:38 AM
jayrajarora2694
jayrajarora2694 - avatar
1 Answer
+ 3
filter takes all elements which match condition, while takewhile takes consecutive elements from beginning which match condition.try out this code: nums=[1,3,5,2,4,7,9] print(list (filter(lambda x:x%2==1,nums))) print(list(takewhile(lambda x:x%2==1,nums))) you will get: 1,3,5,7,9 1,3,5
9th Jul 2016, 4:09 PM
RedAnt
RedAnt - avatar