What is the itertools.takewhile() method in Python?

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.

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 itertools
lst = range(2, 5)
def is_even(x):
return x % 2 == 0
new_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 itertools module.
  • Line 3: We define an iterable of numbers called lst ranging from 2 to 5. We use the range() 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_even method on lst using the takewhile() method. The result is called new_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 itertools
lst = range(2, 5)
is_even = lambda x:x%2==0
new_lst = list(itertools.takewhile(is_even, lst))
print(new_lst)

Code explanation

  • Line 1: We import the itertools module.
  • Line 3: We define an iterable of numbers called lst ranging from 2 to 5 using the range() method.
  • Lines 5: We call a lambda function called is_even that indicates whether a given number is even or odd.
  • Line 7: We apply the is_even lambda function on lst using the takewhile() method. The result is called new_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.

Free Resources