Fibonacci generator

EasyIterator & Generator Programs · 5 of 20

Write a generator that yields Fibonacci numbers, and take the first 10.

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

Approach

  1. An infinite generator plus itertools.islice.

Solution

Python
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.

More iterator & generator programs

← All 20 Iterator & Generator Programs

Leave a Comment