Python Practice › Iterator & Generator Programs › Program 19
Take values while a condition holds
Write a Python program that takes Fibonacci numbers while they are below 100.
Output
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Approach
itertools.takewhile.
Solution
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.