Python Practice › Iterator & Generator Programs › Program 5
Fibonacci generator
Write a generator that yields Fibonacci numbers, and take the first 10.
Output
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Approach
- An infinite generator plus
itertools.islice.
Solution
from itertools import islice def fibonacci(): a, b = 0, 1 while True: yield a a, b = b, a + b print(list(islice(fibonacci(), 10)))Output
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Line by line
Line 9
islice takes the first 10 values from an endless generator.
Learn the concept
New to this topic? Read the lesson, then come back.