0
fibonacci = [0, 1]
fibonacci = [fibonacci.append(fibonacci[i - 1] + fibonacci[i - 2]) for i in range(2, 11)]
print(fibonacci)

This code is supposed to print a list of the first 10 fibonacci numbers. I copied it from another question, but it doesn't seem to work. Why is this?

  • 12
    Because you're putting the result of `append` in a list, and `append` returns None. Either use `append` _or_ use a list comprehension. – khelwood Aug 01 '20 at 18:59
  • You can get it to work by not assigning fibonacci to the list comprehension i.e. just have `[fibonacci.append(fibonacci[i - 1] + fibonacci[i - 2]) for i in range(2, 11)]` though it's discouraged to use list comprehension just for side effects. – DarrylG Aug 01 '20 at 19:03

2 Answers2

2

Unless you love one-liners, in my opinion it makes more sense to write it this way:

fibonacci = [0, 1]
for i in range(2, 11):
    fibonacci.append(fibonacci[i - 1] + fibonacci[i - 2])
Jannes Carpentier
  • 1,838
  • 1
  • 5
  • 12
1

Append will return None. So remove the assignment to the same variable. It will work.

In [11]: fibonacci = [0, 1] 
    ...: [fibonacci.append(fibonacci[i - 1] + fibonacci[i - 2]) for i in range(2, 11)]                                                                                                                      
Out[11]: [None, None, None, None, None, None, None, None, None]

In [12]: print(fibonacci)                                                                                                                                                                                   
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Rahul K P
  • 15,740
  • 4
  • 35
  • 52