TheAlgorithms/Python · error · ValueError

n is negative

Error message

n is negative

What it means

Raised by fib_iterative_yield() in maths/fibonacci.py, a generator yielding the first n Fibonacci numbers, when n is negative. There is no meaningful 'first -1 Fibonacci numbers', so the generator raises ValueError on the first next() before yielding anything.

Source

Thrown at maths/fibonacci.py:57

def fib_iterative_yield(n: int) -> Iterator[int]:
    """
    Calculates the first n (1-indexed) Fibonacci numbers using iteration with yield
    >>> list(fib_iterative_yield(0))
    [0]
    >>> tuple(fib_iterative_yield(1))
    (0, 1)
    >>> tuple(fib_iterative_yield(5))
    (0, 1, 1, 2, 3, 5)
    >>> tuple(fib_iterative_yield(10))
    (0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55)
    >>> tuple(fib_iterative_yield(-1))
    Traceback (most recent call last):
        ...
    ValueError: n is negative
    """
    if n < 0:
        raise ValueError("n is negative")
    a, b = 0, 1
    yield a
    for _ in range(n):
        yield b
        a, b = b, a + b


def fib_iterative(n: int) -> list[int]:
    """
    Calculates the first n (0-indexed) Fibonacci numbers using iteration
    >>> fib_iterative(0)
    [0]
    >>> fib_iterative(1)
    [0, 1]
    >>> fib_iterative(5)
    [0, 1, 1, 2, 3, 5]
    >>> fib_iterative(10)
    [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

View on GitHub (pinned to f5988cc097)

Solutions

  1. Validate n >= 0 at the call site before consuming the generator.
  2. Fix the arithmetic producing the negative count (typically len(x) - k where k > len(x)).
  3. Treat negative input as 'no terms' explicitly: `tuple(fib_iterative_yield(max(n, 0)))` if that semantics is intended.

Example fix

# before
n = total - offset  # negative when offset > total
list(fib_iterative_yield(n))

# after
if n < 0:
    raise ValueError(f'offset {offset} exceeds total {total}')
list(fib_iterative_yield(n))
Defensive patterns

Strategy: validation

Validate before calling

if n < 0:
    raise ValueError(f'n must be >= 0, got {n}')
terms = tuple(fib_iterative_yield(n))

Try / catch

# Generator raises lazily at first next(), so wrap consumption:
try:
    terms = list(fib_iterative_yield(n))
except ValueError as exc:
    raise ValueError(f'invalid fib count {n}') from exc

Prevention

When it happens

Trigger: Calling tuple(fib_iterative_yield(-1)) or iterating the generator with any negative n. Because it is a generator, the ValueError surfaces lazily at first iteration, not at call time.

Common situations: Computing counts from lengths minus offsets (e.g. range sizes from user pagination input), passing a negative slice-derived count, or defaulting missing numeric config to a negative sentinel.

Related errors


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/ce3bfde9a7ae6197. Report an issue: GitHub.