Python Programming - Generators - Discussion

Discussion Forum : Generators - General Questions (Q.No. 79)
79.
What is the purpose of the itertools.takewhile() function when used with generators?
It stops the generator after one iteration
It allows for arbitrary slicing of the generator
It filters elements based on a specified condition until the condition becomes false
It interleaves values from different generators
Answer: Option
Explanation:
itertools.takewhile() yields elements from the generator as long as the specified condition is true, stopping when the condition becomes false.
import itertools

def my_generator():
    for i in range(10):
        yield i

filtered_iterable = itertools.takewhile(lambda x: x < 5, my_generator())

print(list(filtered_iterable))  # Output: [0, 1, 2, 3, 4]
Discussion:
Be the first person to comment on this question !

Post your comments here:

Your comments will be displayed after verification.