pythonlist-comprehensionfibonacci

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.


Solution

  • 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.