An Endless Fibonacci Stream

Easy ⏱ 8 min 72% acceptance ★★★★★ 4.6
Write the generator fib() yielding the Fibonacci sequence forever: 0, 1, 1, 2, 3, … Callers slice what they need with itertools.islice — the generator itself never ends. Demonstrate that consuming 6 values gives [0, 1, 1, 2, 3, 5].

Examples

Example 1
Input
list(islice(fib(), 6))
Output
[0, 1, 1, 2, 3, 5]
Explanation

The infinite stream was sliced lazily.

Constraints

  • No end condition inside the generator.
  • Tuple-swap the pair each step.

Topics

Iterators & Generatorsinfinite generator

Companies

GoogleTCSInfosys

Hints

Hint 1

while True: yield a; a, b = b, a + b.

Hint 2

Generators pause at each yield — no infinite loop hazard.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.