2

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, but I want to have a list of the first n Fib. numbers for future work.

For example:

fib(8) -> [0,1,1,2,3,5,8,13]
Óscar López
  • 225,348
  • 35
  • 301
  • 374
wolfie
  • 23
  • 1
  • 1
  • 5
  • @JTurk Really, don't say *Thank you* in question. – Remi Guan Oct 25 '15 at 03:12
  • i don't follow, can you expound? does this have to do with my edit to the question? – labheshr Oct 25 '15 at 03:14
  • @JTurk Take a look about [this question](http://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-be-removed-from-posts). We really don't need say *Thank you* . Just accept the correct answer or upvote it. – Remi Guan Oct 25 '15 at 03:18

3 Answers3

7

Here's one way using generators....

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

print list(fib(8)) #prints: [0, 1, 1, 2, 3, 5, 8, 13]
labheshr
  • 2,568
  • 2
  • 20
  • 30
4

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

def fib(n):
    if n == 0:
        return [0]
    elif n == 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]
Óscar López
  • 225,348
  • 35
  • 301
  • 374
  • 1
    This worked very well, thanks! I'll definitely play around with this for a bit to learn how to use this sort of coding practice in future cases! – wolfie Oct 25 '15 at 03:03
0

You can acheive it use list:

def fib(n):
  if n <= 0:
     return []
  if n == 1:
     return [0]
  result = [0, 1]
  if n == 2:
     return result
  for i in xrange(2, n):
     result.append(result[i-1] + result[i-2])
  return result
chyoo CHENG
  • 700
  • 2
  • 9
  • 21