Search⌘ K
AI Features

Solution Review: Creating Fibonacci Sequence Using Generator

Understand how to implement the Fibonacci sequence using a generator in Python. Learn to initialize variables, use the yield keyword to output values iteratively, and update values within a loop. This lesson helps you grasp generator behavior and looping for efficient sequence generation.

We'll cover the following...

Solution

...
Python 3.5
def fib_gen(n):
x, y = 0, 1
for _ in range(n):
yield x
x, y = y, x + y
n = 10
gen = fib_gen(n)
print(list(gen))

Explanation

The first thing we need to ...