{"id":25595,"date":"2021-11-23T08:54:46","date_gmt":"2021-11-23T03:24:46","guid":{"rendered":"https:\/\/python-programs.com\/?p=25595"},"modified":"2021-11-23T08:54:46","modified_gmt":"2021-11-23T03:24:46","slug":"python-itertools-takewhile-function-with-examples","status":"publish","type":"post","link":"https:\/\/python-programs.com\/python-itertools-takewhile-function-with-examples\/","title":{"rendered":"Python Itertools.takewhile() Function with Examples"},"content":{"rendered":"

Itertools Module:<\/strong><\/p>\n

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.<\/p>\n

Itertools.takewhile() Function:<\/strong><\/p>\n

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.<\/p>\n

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.<\/p>\n

The predicate can be either a built-in or a user-defined function. Lambda functions can also be used.<\/p>\n

General Implementation Format:<\/strong><\/p>\n

def takewhile_function(gvn_predicte, gvn_itrable):\r\nfor itr in gvn_itrable:\r\n    if gvn_predicte(itr):\r\n        return(itr)\r\n    else:\r\n        break<\/pre>\n

Syntax:<\/strong><\/p>\n

takewhile(predicate, iterable)<\/pre>\n

Parameters<\/strong><\/p>\n

predicate:<\/strong> This is Required. Iterable items are evaluated by the function.<\/p>\n

iterable:<\/strong> This is Required. Elements that will be checked over a predicate.<\/p>\n

Examples:<\/strong><\/p>\n

Example1:<\/strong><\/p>\n

Input:<\/strong><\/p>\n

Given List =  [3, 7, 6, 4, 5, 8]\r\nfunction: num % 2 != 0<\/pre>\n

Output:<\/strong><\/p>\n

[3, 7]<\/pre>\n

Example2:<\/strong><\/p>\n

Input:<\/strong><\/p>\n

Given string =  \"hello123all\"\r\nfunction: character.isalpha()<\/pre>\n

Output:<\/strong><\/p>\n

h\r\ne\r\nl\r\nl\r\no<\/pre>\n

Itertools.takewhile() Function with Examples in Python<\/h2>\n