Generating the Fibonacci Sequence Iteratively
An iterative solution to generate the Fibonacci Sequence
Some months ago I wrote about how to generate any nth number of the Fibonacci Sequence using recursion. As I was reading through my old posts, I felt like I could complete that post with an iterative solution.
Moreover, the iterative solution is far quicker and more efficient than using recursion. As in the other post, I will use Python.
The solution is as easy as this. If you're wondering why I used
nex instead of
next, that's simple because
next is already defined by Python (you can use it to return the next item in an iterator).
def fibonacci(n): prev, nex = 0, 1 for _ in range(n): prev, nex = nex, prev + nex print(prev)
fibonacci function will print out
n values of the sequence. In order to make this simple function even better, we could return the nth value as for the recursive example.
def fibonacci(n): prev, nex = 0, 1 for _ in range(n): prev, nex = nex, prev + nex return prev
If we now call
fibonacci(n) we'll get the nth element of the Fibonacci Sequence (starting from index 1).