Fibonacci Generator in Python

Level 4117 keystrokes

This creates a generator function using yield. Generators produce values lazily, one at a time when iterated.

Python code

# Generator function that yields the first n Fibonacci numbers
1def fibonacci_gen(n):
# Start with the first two Fibonacci numbers, 0 and 1
2 a, b = 0, 1
# Repeat n times; _ marks the loop variable as unused
3 for _ in range(n):
# Yield the current number and pause until the next value is requested
4 yield a
# Move forward: a takes b, and b takes the sum of the previous two
5 a, b = b, a + b
6
# list() runs the generator to the end and collects its 8 values
7fib = list(fibonacci_gen(8))
# Print [0, 1, 1, 2, 3, 5, 8, 13]
8print(fib)

Output

[0, 1, 1, 2, 3, 5, 8, 13]
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • (× 5
  • )× 5
  • ,× 4
  • _× 3
  • =× 3
  • :× 2
  • +× 1

More Python examples at level 4

← Python typing practice