Python Itertools.takewhile() Function with Examples

Itertools Module:

Itertools is a Python module that contains a collection of functions for dealing with iterators. They make it very simple to iterate through iterables such as lists and strings.

Itertools.takewhile() Function:

This allows you to consider an iterable item until the specified predicate becomes false for the first time. In most cases, the iterable is a list or a string.

It “takes” the element from the sequence “while” the predicate is “true,” as the name implies. This function belongs to the category of “terminating iterators.” The output cannot be used directly and must be converted to another iterable form before it can be used. They are mostly converted into lists.

The predicate can be either a built-in or a user-defined function. Lambda functions can also be used.

General Implementation Format:

def takewhile_function(gvn_predicte, gvn_itrable):
for itr in gvn_itrable:
    if gvn_predicte(itr):
        return(itr)
    else:
        break

Syntax:

takewhile(predicate, iterable)

Parameters

predicate: This is Required. Iterable items are evaluated by the function.

iterable: This is Required. Elements that will be checked over a predicate.

Examples:

Example1:

Input:

Given List =  [3, 7, 6, 4, 5, 8]
function: num % 2 != 0

Output:

[3, 7]

Example2:

Input:

Given string =  "hello123all"
function: character.isalpha()

Output:

h
e
l
l
o

Itertools.takewhile() Function with Examples in Python

Method #1: Using Built-in Functions (Static Input)

1)For Lists

Approach:

  • Import takewhile() function from itertools using the import keyword.
  • Create a function say check_oddnumbers which accepts the number as an argument and returns True if it is an odd number.
  • Inside the function, Return if the number is odd.
  • Give the list as static input and store it in a variable.
  • Pass the above function(check_oddnumbers) and given list as the arguments to the takewhile() function where check_oddnumbers()  function returns the odd numbers.
  • Store it in another variable.
  • Convert the above result into a list using the list() function and store it in another variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Import takewhile() function from itertools using the import keyword.
from itertools import takewhile

# Create a function say check_oddnumbers which accepts the number as an argument and
# returns True if it is an odd number


def check_oddnumbers(num):
    # Return if the number is odd.
    return(num % 2 != 0)


# Give the list as static input and store it in a variable.
gvn_lst = [3, 7, 6, 4, 5, 8]
# Pass the above function(check_oddnumbers) and given list as the arguments to the
# takewhile() function where check_oddnumbers() function returns the odd numbers
# and store it in another variable.
rslt = takewhile(check_oddnumbers, gvn_lst)
# Convert the above result into a list using the list() function and store it in
# another variable.
rslt_lst = list(rslt)
# Print the above result.
print(rslt_lst)

Output:

[3, 7]
2)For Strings

Approach:

  • Import takewhile() function from itertools using the import keyword.
  • Create a function say check_isalpha which accepts the character as an argument and returns True if the character is an alphabet.
  • Inside the function, Return if the argument(character) is an alphabet.
  • Give the string as static input and store it in a variable.
  • Loop using the takewhile() function and for loop by passing the arguments as the above check_isalpha function and given string.
  • Inside the loop, print the iterator value.
  • The Exit of the Program.

Below is the implementation:

# Import takewhile() function from itertools using the import keyword.
from itertools import takewhile

# Create a function say check_isalpha which accepts the character as an argument
# and returns True if the character is an alphabet.


def check_isalpha(ch):
    # Return if the argument(character) is an alphabet.
    return(ch.isalpha())


# Give the string as static input and store it in a variable.
gvn_str = "hello1234all"
# Loop using the takewhile() function and for loop by passing the arguments as
# the above check_isalpha function and given string.

for itr in takewhile(check_isalpha, gvn_str):
    # Inside the loop, print the iterator value.
    print(itr)

Output:

h
e
l
l
o

Method #2: Using Built-in Functions (User Input)

Approach:

  • Import takewhile() function from itertools using the import keyword.
  • Create a function say check_oddnumbers which accepts the number as an argument and returns True if it is an odd number.
  • Inside the function, Return if the number is odd.
  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Pass the above function(check_oddnumbers) and given list as the arguments to the takewhile() function where check_oddnumbers()  function returns the odd numbers.
  • Store it in another variable.
  • Convert the above result into a list using the list() function and store it in another variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Import takewhile() function from itertools using the import keyword.
from itertools import takewhile

# Create a function say check_oddnumbers which accepts the number as an argument and
# returns True if it is an odd number


def check_oddnumbers(num):
    # Return if the number is odd.
    return(num % 2 != 0)


# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gvn_lst = list(map(int, input(
   'Enter some random List Elements separated by spaces = ').split()))

# Pass the above function(check_oddnumbers) and given list as the arguments to the
# takewhile() function where check_oddnumbers function returns the odd numbers.
# Store it in another variable.
rslt = takewhile(check_oddnumbers, gvn_lst)
# Convert the above result into a list using the list() function and store it in
# another variable.
rslt_lst = list(rslt)
# Print the above result.
print(rslt_lst)

Output:

Enter some random List Elements separated by spaces = 9 7 5 2 8 3
[9, 7, 5]
2)For Strings

Approach:

  • Import takewhile() function from itertools using the import keyword.
  • Create a function say check_isalpha which accepts the character as an argument and returns True if the character is an alphabet.
  • Inside the function, Return if the argument(character) is an alphabet.
  • Give the string as user input using the input() function and store it in a variable.
  • Loop using the takewhile() function and for loop by passing the arguments as the above check_isalpha function and given string.
  • Inside the loop, print the iterator value.
  • The Exit of the Program.

Below is the implementation:

# Import takewhile() function from itertools using the import keyword.
from itertools import takewhile

# Create a function say check_isalpha which accepts the character as an argument
# and returns True if the character is an alphabet.


def check_isalpha(ch):
    # Return if the character is an alphabet.
    return(ch.isalpha())


# Give the string as user input using the input() function and store it in a variable.
gvn_str = input("Enter some random string = ")
# Loop using the takewhile function and for loop by passing the arguments as
# the above check_isalpha function and given string.

for itr in takewhile(check_isalpha, gvn_str):
    # Inside the loop, print the iterator value.
    print(itr)

Output:

Enter some random string = abc567yiu
a
b
c