Home > Software design >  Fibonacci function with list comprehension returns None
Fibonacci function with list comprehension returns None

Time:08-19

Returns [None,None,None,None,None]

def perimeter(num):
    lst = [1]
    return [lst.append(n lst[lst.index(n)-1]) for n in lst if len(lst) <= num]

print(perimeter(5))

CodePudding user response:

lst.append(...) doesn't return anything (more precisely, returns None).

Your function returns the list created with the list comprehenshion . This list contains 5 results of lst.append(...) - which are all None.


What you technically can do, is return lst from the function:

def perimeter(num):
    lst = [1]
    [lst.append(n lst[lst.index(n)-1]) for n in lst if len(lst) <= num]
    return lst
print(perimeter(5))
[1, 2, 3, 5, 8, 13]
  • Related