+ 7

What's the difference between the itertool takewhile and the filter module? They seem to be the same thing

14th Dec 2018, 7:37 AM
Vlad Cretu
Vlad Cretu - avatar
4 Answers
+ 15
filter scans the whole iterator for elements matching the condition. itertools.takewhile stops the moment it finds an element that doesn't fit the condition. Demo code: from itertools import takewhile my_list = [1, -2, 3, -4, 5, -6] print(list(takewhile(lambda x: x>0, my_list))) # outputs [1] print(list(filter(lambda x: x>0, my_list))) # outputs [1, 3, 5]
14th Dec 2018, 7:54 AM
Kishalaya Saha
Kishalaya Saha - avatar
+ 4
You're very welcome, Vlad Cretu ! 😊 I saw that you've only been here a week. You're a fast learner! Good for you 👌
14th Dec 2018, 7:59 AM
Kishalaya Saha
Kishalaya Saha - avatar
+ 2
Aaaa, ok I understand now. Thank you :)
14th Dec 2018, 7:56 AM
Vlad Cretu
Vlad Cretu - avatar
- 1
"#099x10";
14th Dec 2018, 10:25 AM
Gjjf Ggnhg