Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create the fibonacci series using a list comprehension?

I am new to python, and I was wondering if I could generate the fibonacci series using python's list comprehension feature. I don't know how list comprehensions are implemented. I tried the following (the intention was to generate the first five fibonacci numbers):

series=[]
series.append(1)
series.append(1)
series += [series[k-1]+series[k-2] for k in range(2,5)]

This piece of code throws the error: IndexError: list index out of range.

Let me know if it is even possible to generate such a series using a list comprehension.

like image 612
Thenavats Avatar asked Feb 21 '17 14:02

Thenavats


People also ask

How do you list a Fibonacci sequence?

Fibonacci Sequence List. The list of first 20 terms in the Fibonacci Sequence is: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181. … and so on.


1 Answers

You cannot do it like that: the list comprehension is evaluated first, and then that list is added to series. So basically it would be like you would have written:

series=[]
series.append(1)
series.append(1)
temp = [series[k-1]+series[k-2] for k in range(2,5)]
series += temp

You can however solve this by using list comprehension as a way to force side effects, like for instance:

series=[]
series.append(1)
series.append(1)
[series.append(series[k-1]+series[k-2]) for k in range(2,5)]

Note that we here do not add the result to series. The list comprehension is only used such that .append is called on series. However some consider list comprehensions with side effects rather error prone: it is not very declarative and tends to introduce bugs if not done carefully.

like image 200
Willem Van Onsem Avatar answered Sep 19 '22 07:09

Willem Van Onsem