Skip to content Skip to sidebar Skip to footer

Python: Creating A List Of The First N Fibonacci Numbers

I am new to Python and to these forums. My question is: How can I create a list of n Fibonacci numbers in Python? So far, I have a function that gives the nth Fibonacci number, b

Solution 1:

Here's one way using generators....

def fib(n):
    a, b =0, 1for _ in xrange(n):
        yield a
        a, b = b, a + b

print list(fib(8))#prints: [0, 1, 1, 2, 3, 5, 8, 13]

Solution 2:

Try this, a recursive implementation that returns a list of numbers by first calculating the list of previous values:

def fib(n):
    ifn== 0:
        return [0]
    elifn== 1:
        return [0, 1]
    else:
        lst = fib(n-1)
        lst.append(lst[-1] + lst[-2])
        return lst

It works as expected:

fib(8)
=> [0, 1, 1, 2, 3, 5, 8, 13, 21]

Solution 3:

You can acheive it use list:

def fib(n):
  if n <=0:
     return []
  if n ==1:
     return [0]
  result= [0, 1]
  if n ==2:
     returnresultfor i in xrange(2, n):
     result.append(result[i-1] +result[i-2])
  returnresult

Post a Comment for "Python: Creating A List Of The First N Fibonacci Numbers"