Efficient Pythonic generator of the Fibonacci sequence
I found this question while trying to get the shortest Pythonic generation of this sequence and I haven't noticed anyone else coming up with my specific solution (although the top answer gets close, but still less elegant), so here it is, with comments describing the first iteration, because I think that may help readers understand:
def fib():
a, b = 0, 1
while True:
# First iteration:
yield a
# yield 0 to start with and then
a, b = b, a + b # a will now be 1, and b will also be 1, (0 + 1)
and usage:
for index, fibonacci_number in zip(range(10), fib()):
print('{i:3}:
{f:3}'.format(i=index, f=fibonacci_number))
prints:
0: 0
1: 1
2: 1
3: 2
4: 3
5: 5
6: 8
7: 13
8: 21
9: 34
10: 55