Editor

Fibonacci Sequence

Loops · Intermediate · 70 XP · about 7 min

Write a function called fibonacci(n) that returns a list of the first n Fibonacci numbers.

The Fibonacci sequence starts with 0, 1, and each subsequent number is the sum of the two preceding numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...

Example

fibonacci(5)   # Returns [0, 1, 1, 2, 3]
fibonacci(1)   # Returns [0]
fibonacci(2)   # Returns [0, 1]
fibonacci(10)  # Returns [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Requirements

  • Return a list starting from 0
  • Handle n = 1 and n = 2 as edge cases
  • You can assume n >= 1
def fibonacci(n):
# Your code here
pass
# Test your function
print(fibonacci(10))

Ready?

Accept the challenge to start writing. A small timer counts the time this page is in view.

Output appears here.