Menu Close

How to generate the Fibonacci Sequence with Python?

Sometimes, we want to generate the Fibonacci Sequence with Python.

In this article, we’ll look at how to generate the Fibonacci Sequence with Python.

How to generate the Fibonacci Sequence with Python?

To generate the Fibonacci Sequence with Python, we can create a generator function that yields the value the sequence.

For instance, we write:

def fib():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b


for index, fibonacci_number in zip(range(10), fib()):
    print(index, fibonacci_number)

We create the fib function that uses yield to return the Fibonacci sequence by assigning b to a and b to a + b.

Then we use a for loop that zips range(10) and the iterator returned by the fib function together to generate the first 10 Fibonacci sequence values.

In the loop body, we print the index and fibonacci_number values.

Therefore, we see:

0 0
1 1
2 1
3 2
4 3
5 5
6 8
7 13
8 21
9 34

logged.

Conclusion

To generate the Fibonacci Sequence with Python, we can create a generator function that yields the value the sequence.

Posted in Python, Python Answers