What's the difference between the itertool takewhile and the filter module? They seem to be the same thing | Sololearn: Learn to code for FREE!

+7

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

12/14/2018 7:37:25 AM

Vlad Cretu

4 Answers

New Answer

+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]

+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 👌

+2

Aaaa, ok I understand now. Thank you :)

-1

"#099x10";