Take values while a condition holds

EasyIterator & Generator Programs · 19 of 20

Write a Python program that takes Fibonacci numbers while they are below 100.

Advertisement
Output
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

Approach

  1. itertools.takewhile.

Solution

Python
from itertools import takewhile def fibonacci():    a, b = 0, 1    while True:        yield a        a, b = b, a + b print(list(takewhile(lambda n: n < 100, fibonacci())))
Output
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

Learn the concept

New to this topic? Read the lesson, then come back.

More iterator & generator programs

← All 20 Iterator & Generator Programs

Leave a Comment