Note:
itertools
is 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
.
takewhile(predicate, iterable)
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.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)
itertools
module.lst
ranging from 2
to 5
. We use the range()
method for this.is_even
. This indicates whether a given number is even or odd.is_even
method on lst
using the takewhile()
method. The result is called new_lst
.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.
import itertoolslst = range(2, 5)is_even = lambda x:x%2==0new_lst = list(itertools.takewhile(is_even, lst))print(new_lst)
itertools
module.lst
ranging from 2
to 5
using the range()
method.is_even
that indicates whether a given number is even or odd.is_even
lambda function on lst
using the takewhile()
method. The result is called new_lst
.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.