TheAlgorithms/Python · error · ValueError

Both the weights and values vectors must be either lists or

Error message

Both the weights and values vectors must be either lists or tuples

What it means

Raised by knapsack_with_example_solution(w, wt, val) when either wt or val is not a list or tuple (checked with isinstance(wt, (list, tuple)) and isinstance(val, (list, tuple))). The 0/1 knapsack DP needs indexed access to weights and values, so generators and other sequences are rejected. It is the first validation in the function, before length and element-type checks.

Source

Thrown at dynamic_programming/knapsack.py:77

    * `optimal_val`: float, the optimal value for the given knapsack problem
    * `example_optional_set`: set, the indices of one of the optimal subsets
      which gave rise to the optimal value.

    Examples
    --------

    >>> knapsack_with_example_solution(10, [1, 3, 5, 2], [10, 20, 100, 22])
    (142, {2, 3, 4})
    >>> knapsack_with_example_solution(6, [4, 3, 2, 3], [3, 2, 4, 4])
    (8, {3, 4})
    >>> knapsack_with_example_solution(6, [4, 3, 2, 3], [3, 2, 4])
    Traceback (most recent call last):
        ...
    ValueError: The number of weights must be the same as the number of values.
    But got 4 weights and 3 values
    """
    if not (isinstance(wt, (list, tuple)) and isinstance(val, (list, tuple))):
        raise ValueError(
            "Both the weights and values vectors must be either lists or tuples"
        )

    num_items = len(wt)
    if num_items != len(val):
        msg = (
            "The number of weights must be the same as the number of values.\n"
            f"But got {num_items} weights and {len(val)} values"
        )
        raise ValueError(msg)
    for i in range(num_items):
        if not isinstance(wt[i], int):
            msg = (
                "All weights must be integers but got weight of "
                f"type {type(wt[i])} at index {i}"
            )
            raise TypeError(msg)

View on GitHub (pinned to f5988cc097)

Solutions

  1. Materialize sequences before the call: knapsack(w, list(wt), list(val)).
  2. Convert numpy arrays with .tolist().
  3. Add a precondition assert isinstance(wt, (list, tuple)) and isinstance(val, (list, tuple)).

Example fix

# before
best = knapsack_with_example_solution(10, (abs(x) for x in raw), [1,2,3,4])

# after
best = knapsack_with_example_solution(10, [abs(x) for x in raw], [1,2,3,4])
Defensive patterns

Strategy: type-guard

Validate before calling

if not (isinstance(wt, (list, tuple)) and isinstance(val, (list, tuple))):
    wt, val = list(wt), list(val)
optimal, picked = knapsack_with_example_solution(w, wt, val)

Type guard

def is_sequence_pair(a: object, b: object) -> bool:
    return isinstance(a, (list, tuple)) and isinstance(b, (list, tuple))

Try / catch

try:
    optimal, picked = knapsack_with_example_solution(w, wt, val)
except ValueError as exc:
    if 'lists or tuples' in str(exc):
        optimal, picked = knapsack_with_example_solution(w, list(wt), list(val))
    else:
        raise

Prevention

When it happens

Trigger: Passing a generator or map object, e.g. knapsack_with_example_solution(10, map(abs, w), [1,2,3,4]); passing a numpy array, set, or string as weights or values; passing None for one of the vectors.

Common situations: Chaining map/filter generators from upstream data processing; using numpy arrays from numerical pipelines without conversion; JSON deserialization yielding something other than arrays.

Related errors


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