{"record":{"id":"54bcec1f6afb445f","repo":"jax-ml/jax","slug":"with-nc-condition-s-either-nc-or-nc-1-func","errorCode":null,"errorMessage":"with {nc} condition(s), either {nc} or {nc+1} functions are expected; got {nf}","messagePattern":"with (.+?) condition\\(s\\), either (.+?) or (.+?) functions are expected; got (.+?)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"jax/_src/numpy/lax_numpy.py","lineNumber":9561,"sourceCode":"    >>> jnp.piecewise(x, condlist, funclist)\n    Array([-3, -2,  -1,  0,  0,  0,  1,  2, 3], dtype=int32)\n\n    ``condlist`` may also be a simple array of scalar conditions, in which case\n    the associated function applies to the whole range\n\n    >>> condlist = jnp.array([False, True, False])\n    >>> funclist = [lambda x: x * 0, lambda x: x * 10, lambda x: x * 100]\n    >>> jnp.piecewise(x, condlist, funclist)\n    Array([-40, -30, -20, -10,   0,  10,  20,  30,  40], dtype=int32)\n  \"\"\"\n  x_arr = util.ensure_arraylike(\"piecewise\", x)\n  nc, nf = len(condlist), len(funclist)\n  if nf == nc + 1:\n    funclist = funclist[-1:] + funclist[:-1]\n  elif nf == nc:\n    funclist = [0] + list(funclist)\n  else:\n    raise ValueError(f\"with {nc} condition(s), either {nc} or {nc+1} functions are expected; got {nf}\")\n  consts = {i: c for i, c in enumerate(funclist) if not callable(c)}\n  funcs = {i: f for i, f in enumerate(funclist) if callable(f)}\n  return _piecewise(x_arr, asarray(condlist, dtype=bool), consts,\n                    frozenset(funcs.items()),  # dict is not hashable.\n                    *args, **kw)\n\n@api.jit(static_argnames=['funcs'])\ndef _piecewise(x: Array, condlist: Array, consts: dict[int, ArrayLike],\n               funcs: frozenset[tuple[int, Callable[..., Array]]],\n               *args, **kw) -> Array:\n  funcdict = dict(funcs)\n  funclist = [consts.get(i, funcdict.get(i)) for i in range(len(condlist) + 1)]\n  indices = argmax(reductions.cumsum(concatenate(\n      [array_creation.zeros_like(condlist[:1]), condlist], 0), 0), 0)\n  dtype = x.dtype\n  def _call(f):\n    return lambda x: f(x, *args, **kw).astype(dtype)\n  def _const(v):","sourceCodeStart":9543,"sourceCodeEnd":9579,"githubUrl":"https://github.com/jax-ml/jax/blob/1e1c6a8fc06dfcd1247076ec5cae4640cea5d7bb/jax/_src/numpy/lax_numpy.py#L9543-L9579","documentation":"jnp.piecewise evaluates a piecewise function from a list of conditions and a corresponding list of functions/values. The number of funclist entries must equal the number of conditions or be exactly one more (a default); any other count raises ValueError('with {nc} condition(s), either {nc} or {nc+1} functions are expected; got {nf}').","triggerScenarios":"jnp.piecewise(x, [c1, c2], [f1]) — 2 conditions with 1 function; or 3 functions for 1 condition.","commonSituations":"Adding/removing a condition branch without updating funclist; passing a default value without the corresponding extra slot layout piecewise expects.","solutions":["Make len(funclist) == len(condlist) or len(condlist) + 1","Add a default function/value as the extra entry when using nc+1","Count both lists before the call"],"exampleFix":"// before\njnp.piecewise(x, [x < 0, x >= 0], [lambda x: -x])  # ValueError\n// after\njnp.piecewise(x, [x < 0, x >= 0], [lambda x: -x, lambda x: x])","handlingStrategy":"validation","validationCode":"assert len(funclist) in (len(condlist), len(condlist) + 1), \\\n    f'need {len(condlist)} or {len(condlist)+1} functions, got {len(funclist)}'\njnp.piecewise(x, condlist, funclist)","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Keep condlist and funclist lengths in sync","Provide a default as the extra function","Re-count lists after editing branches"],"tags":["jax","piecewise","list-length-mismatch"],"backgroundTag":"argument-count-mismatch","analyzedSha":"1e1c6a8fc06dfcd1247076ec5cae4640cea5d7bb","analyzedAt":"2026-08-27T09:53:25.647Z","schemaVersion":2},"datasetVersion":"2026-08-27T13:17:12.746Z"}