Why does this code output a list of "None"?
Question:
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?
Answers:
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]
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])
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?
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]
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])