typestar

Fibonacci generator in Python

Generators produce values lazily - infinite sequences without infinite memory.

def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

def take(gen, n):
    return [next(gen) for _ in range(n)]

How it works

  1. Defines a generator that runs forever.
  2. Each yield hands out the next Fibonacci number on demand.
  3. take() pulls the first n values with next().

Keywords and builtins used here

The run, in numbers

Lines
8
Characters to type
120
Tokens
48
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 30 seconds.

Type this snippet

Step 2 of 7 in Iterators, errors & files, step 45 of 72 in Language basics.

← Previous Next →