What is the itertools.takewhile() method in Python?
Note:
itertoolsis a module in Python that provides functions. These functions help in iterating through iterables.
The takewhile() method in the itertools module accepts a predicate and an iterable. The method returns the elements of the iterable until the predicate is true. The iteration stops when the predicate for any element is false.
We get two words when we break the method name, i.e., take and while. This means it takes elements while the predicate for those elements returns true.
Syntax
takewhile(predicate, iterable)
Parameters
predicate: This is the predicate function that accepts an input and returns a boolean value. It can be a built-in, user-defined, or lambda function.iterable: This is the list or the string over which this method is applied.
Coding example 1 (The User-defined function as predicate)
import itertoolslst = range(2, 5)def is_even(x):return x % 2 == 0new_lst = list(itertools.takewhile(is_even, lst))print("Original List - ", list(lst))print("List after applying takewhile - ", new_lst)
Code explanation
- Line 1: We import the
itertoolsmodule. - Line 3: We define an iterable of numbers called
lstranging from2to5. We use therange()method for this. - Lines 5-6: We define a method called
is_even. This indicates whether a given number is even or odd. - Line 8: We apply the
is_evenmethod onlstusing thetakewhile()method. The result is callednew_lst. - Line 11: We print
new_lst.
The output consists only of the number 2. This is because the number after 2 in lst is 3 for which the is_even predicate fails. Therefore, the iteration stops with 2 as the only element in the output.
Coding example 2 - (The Lambda function as predicate)
import itertoolslst = range(2, 5)is_even = lambda x:x%2==0new_lst = list(itertools.takewhile(is_even, lst))print(new_lst)
Code explanation
- Line 1: We import the
itertoolsmodule. - Line 3: We define an iterable of numbers called
lstranging from2to5using therange()method. - Lines 5: We call a lambda function called
is_eventhat indicates whether a given number is even or odd. - Line 7: We apply the
is_evenlambda function onlstusing thetakewhile()method. The result is callednew_lst. - Line 9: We print
new_lst.
The output consists only of the number 2. This is because the next number after 2 in lst is 3, for which the is_even predicate fails. Therefore, the iteration stops with 2 as the only element in the output.