Breaking News: Grepper is joining You.com. Read the official announcement!
Check it out

9. itertools.takewhile(): Filter Elements in a Different Way

Sumit Rawal answered on May 13, 2023 Popularity 1/10 Helpfulness 1/10

Contents


More Related Answers

  • 2. itertools.compress(): A Convenient Way To Filter Data
  • 10. itertools.dropwhile(): A Reverse Operation of itertools.takewhile()

  • 9. itertools.takewhile(): Filter Elements in a Different Way

    0

    itertools.takewhile() returns an iterator that generates elements from an iterable as long as a given predicate function evaluates to True.

    import itertools

    nums = [1, 61, 7, 9, 2077]

    print(list(itertools.takewhile(lambda x: x < 100, nums)))

    # [1, 61, 7, 9]

    This function is different from the built-in filter() function.

    The filter function will go through the whole list:

    nums = [1, 61, 7, 9, 2077]

    print(list(filter(lambda x: x < 10, nums)))

    # [1, 7, 9]

    However, the itertools.takewhile function, as its name implies, will stop when the evaluating function is False:

    import itertools

    nums = [1, 61, 7, 9, 2077]

    print(list(itertools.takewhile(lambda x: x < 10, nums)))

    # [1]  

    Popularity 1/10 Helpfulness 1/10 Language typescript
    Source: Grepper
    Link to this answer
    Share Copy Link
    Contributed on May 13 2023
    Sumit Rawal
    0 Answers  Avg Quality 2/10


    X

    Continue with Google

    By continuing, I agree that I have read and agree to Greppers's Terms of Service and Privacy Policy.
    X
    Grepper Account Login Required

    Oops, You will need to install Grepper and log-in to perform this action.