Python - Itertools.takewhile()
Last Updated :
19 Feb, 2020
The
itertools is a module in Python having a collection of functions that are used for handling iterators. They make iterating through the iterables like lists and strings very easy. One such itertools function is
takewhile()
.
Note: For more information, refer to
Python Itertools
takewhile()
This allows considering an item from the iterable until the specified predicate becomes false for the first time. The iterable is a list or string in most of the cases. As the name suggests it
"take" the element from the sequence
"while" the predicate is
"true". This function come under the category
"terminating iterators". The output cannot be used directly and has to be converted to another iterable form. Mostly they are converted into lists.
Syntax:
takewhile(predicate, iterable)
The
predicate
is either a built-in function or a user-defined function. It can be even lambda functions.
The general implementation of this function using simple if-else is given below.
def takewhile(predicate, iterable):
for i in iterable:
if predicate(i):
return(i)
else:
break
The function
takewhile()
takes a predicate and an iterable as arguments. The iterable is iterated to check each of its elements. If the elements on the specified predicate, evaluates to true, it is returned. Otherwise, the loop is terminated.
Example 1: Lists and takewhile()
Consider a list of integers. We need only the even numbers in the output. Look at the code below to see what happens if we use
takewhile()
.
Python3 1==
from itertools import takewhile
# function to check whether
# number is even
def even_nos(x):
return(x % 2 == 0)
# iterable (list)
li =[0, 2, 4, 8, 22, 34, 6, 67]
# output list
new_li = list(takewhile(even_nos, li))
print(new_li)
Output:
[0, 2, 4, 8, 22, 34, 6]
Example 2: Strings and takewhile()
Consider an alpha-numerical String. Now we need to take the elements as long as they are digits.
Python3 1==
from itertools import takewhile
# function to test the elements
def test_func(x):
print("Testing:", x)
return(x.isdigit())
# using takewhile with for-loop
for i in takewhile(test_func, "11234erdg456"):
print("Output :", i)
print()
Output:
Testing: 1
Output : 1
Testing: 1
Output : 1
Testing: 2
Output : 2
Testing: 3
Output : 3
Testing: 4
Output : 4
Testing: e
The iterable can be directly passed also. It is not mandatory that they should be assigned to some variable before passing them to
takewhile()
function.
Example 3: lambda functions in takewhile()
Consider the elements of the input String until a 's' is encountered.
Python3 1==
from itertools import takewhile
# input string
st ="GeeksforGeeks"
# consider elements until
# 's' is encountered
li = list(takewhile(lambda x:x !='s', st))
print(li)
Output:
['G', 'e', 'e', 'k']
Example 4:
Make a list of alphabets in random order and consider the elements until you encounter 'e' or 'i' or 'u'.
Python3 1==
import random
from itertools import takewhile
# generating alphabets in random order
li = random.sample(range(97, 123), 26)
li = list(map(chr, li))
print("The original list list is :")
print(li)
# consider the element until
# 'e' or 'i' or 'o' is encountered
new_li = list(takewhile(lambda x:x not in ['e', 'i', 'o'],
li))
print("\nThe new list is :")
print(new_li)
Output:
The original list list is :
['v', 'u', 'k', 'j', 'r', 'q', 'n', 'y', 'a', 'x', 'i', 'p', 'e', 'w', 'b', 't', 's', 'l', 'z', 'm', 'f', 'c', 'g', 'd', 'o', 'h']
The new list is :
['v', 'u', 'k', 'j', 'r', 'q', 'n', 'y', 'a', 'x']
Similar Reads
Python Itertools
Python's Itertool is a module that provides various functions that work on iterators to produce complex iterators. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra. For example, let's suppose there are two lists and we wa
12 min read
Python - Itertools.count()
Python Itertools are a great way of creating complex iterators which helps in getting faster execution time and writing memory-efficient code. Itertools provide us with functions for creating infinite sequences and itertools.count() is one such function and it does exactly what it sounds like, it co
3 min read
Python - Itertools.cycle()
Iterator is defined as object types which contains values that can be accessed or iterated using a loop. There are different iterators that come built-in with Python such as lists, sets, etc. Itertools is the Python module that contains some inbuilt functions for generating sequences using iterators
3 min read
Python - itertools.repeat()
Pythonâs Itertool is a module that provides various functions that work on iterators to produce complex iterators. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra. Note: For more information, refer to Python Itertools re
2 min read
Itertools.accumulate()-Python
itertools.accumulate() is an iterator that takes two arguments, an iterable (target) and an optional function. The function is applied at each iteration to accumulate the result. By default, if no function is provided, it performs addition. If the input iterable is empty, the output will also be emp
3 min read
Python - Itertools.chain()
The itertools is a module in Python having a collection of functions that are used for handling iterators. They make iterating through the iterables like lists and strings very easily. One such itertools function is chain().Note: For more information, refer to Python Itertools chain() function It is
4 min read
Python - Itertools.chain.from_iterable()
Python's Itertool is a module that provides various functions that work on iterators to produce complex iterators. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra. Note: For more information, refer to Python Itertools Th
2 min read
Python - Itertools.compress()
Pythonâs Itertool is a module that provides various functions that work on iterators to produce complex iterators. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra. Note: For more information, refer to Python Itertools Co
2 min read
Python - Itertools.dropwhile()
Itertools is a Python module that provide various functions that work on iterators to produce complex iterators. It makes the code faster, memory efficient and thus we see a better performance. This module is either used by themselves or in combination to form iterator algebra. Note: For more inform
1 min read
Python - Itertools.filterfalse()
In Python, Itertools is the inbuilt module that allows us to handle the iterators in an efficient way. They make iterating through the iterables like lists and strings very easily. One such itertools function is filterfalse(). Note: For more information, refer to Python Itertools filterfalse() funct
2 min read