Skip to main content

Mojo function

take_while

take_while[origin: ImmutOrigin, IterableType: Iterable, //, predicate: fn(IterableType.IteratorType[False, origin._mlir_origin, origin].Element) -> Bool](ref[origin] iterable: IterableType) -> _TakeWhileIterator[predicate]

Creates an iterator that yields elements while predicate returns True.

This function returns an iterator that yields elements from the input iterable as long as the predicate function returns True for each element. Once the predicate returns False, the iterator stops immediately and does not yield any more elements.

Examples:

from itertools import take_while

# Take while less than 5
fn less_than_5(x: Int) -> Bool:
    return x < 5

var nums = [1, 2, 3, 4, 5, 6, 7]
for num in take_while[less_than_5](nums):
    print(num)  # Prints: 1, 2, 3, 4

Parameters:

  • ​origin (ImmutOrigin): The origin of the iterable.
  • ​IterableType (Iterable): The type of the iterable.
  • ​predicate (fn(IterableType.IteratorType[False, origin._mlir_origin, origin].Element) -> Bool): A function that takes an element and returns True if the element should be yielded.

Args:

  • ​iterable (IterableType): The iterable to take elements from.

Returns:

_TakeWhileIterator: An iterator that yields elements while predicate returns True.

Was this page helpful?