{"record":{"id":"bae3c066c3a03cf7","repo":"jax-ml/jax","slug":"iteration-over-a-0-d-array","errorCode":null,"errorMessage":"iteration over a 0-d array","messagePattern":"iteration over a 0-d array","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"jax/_src/array.py","lineNumber":346,"sourceCode":"  def __format__(self, format_spec):\n    if isinstance(self.sharding, NamedSharding) and self.sharding.spec.unreduced:\n      return repr(self)\n    elif (self.is_fully_addressable or self.is_fully_replicated and\n          self.sharding.has_addressable_devices):\n      # Simulates behavior of https://github.com/numpy/numpy/pull/9883\n      return format(self._value if self.ndim else self._value[()], format_spec)\n    else:\n      return repr(self)\n\n  def __getitem__(self, idx, /):\n    from jax._src.numpy import indexing  # pyrefly: ignore[missing-import]\n    self._check_if_deleted()\n\n    return indexing.rewriting_take(self, idx)\n\n  def __iter__(self):\n    if self.ndim == 0:\n      raise TypeError(\"iteration over a 0-d array\")  # same as numpy error\n    else:\n      assert self.is_fully_replicated or self.is_fully_addressable\n      if self.sharding.num_devices == 1 or self.is_fully_replicated:\n        return (sl for chunk in self._chunk_iter(100) for sl in chunk._unstack())  # pyrefly: ignore[missing-attribute]\n      else:\n        # TODO(yashkatariya): Don't bounce to host and use `_chunk_iter` path\n        # here after uneven partitioning support is added.\n        return (api.device_put(self._value[i]) for i in range(self.shape[0]))\n\n  @property\n  def is_fully_replicated(self) -> bool:\n    return self.sharding.is_fully_replicated\n\n  def __repr__(self):\n    prefix = 'Array('\n    if self.aval is not None and self.aval.weak_type:\n      dtype_str = f'dtype={self.dtype.name}, weak_type=True'\n    else:","sourceCodeStart":328,"sourceCodeEnd":364,"githubUrl":"https://github.com/jax-ml/jax/blob/1e1c6a8fc06dfcd1247076ec5cae4640cea5d7bb/jax/_src/array.py#L328-L364","documentation":"jax.Array.__iter__ raises TypeError when iterating over a 0-d (scalar) array, mirroring NumPy's behavior since scalars are not iterable. JAX implements the Python iteration protocol only for arrays with ndim >= 1. The error is raised before any sharding/addressability checks.","triggerScenarios":"Calling list(x), for v in x, tuple(x), or *x unpacking on an Array with x.ndim == 0, e.g. the result of jnp.squeeze, .sum(), .mean(), or indexing a 1-d array with a single int.","commonSituations":"Computing a scalar loss/accuracy and accidentally iterating it; aggressive jnp.squeeze removing all dims; functions that accept 'array or scalar' and do `for item in arg`; switching code from Python floats (iterable via string repr confusion) or assuming jnp scalars behave like 1-element lists.","solutions":["Use x.item() to extract the Python scalar: float(x.item())","Reshape to 1-d before iterating: x.reshape(1) or x[None]","Check rank first: if x.ndim == 0: handle scalar path","Use jnp.atleast_1d(x) before generic iteration code"],"exampleFix":"// before\nloss = jnp.mean(preds - targets)\nfor v in loss:  # TypeError: iteration over a 0-d array\n  ...\n// after\nloss = jnp.mean(preds - targets)\nval = loss.item()\n# or iterate a 1-d view:\nfor v in jnp.atleast_1d(loss):\n  ...","handlingStrategy":"type-guard","validationCode":"def is_scalar_array(x):\n    return hasattr(x, 'ndim') and x.ndim == 0\n\nif is_scalar_array(loss):\n    total = loss.item()\nelse:\n    total = float(jnp.sum(loss))","typeGuard":"from jax import Array\nimport numpy as np\n\ndef is_zero_dim(x) -> bool:\n    \"\"\"True for jax arrays, ndarrays, or scalars with ndim == 0.\"\"\"\n    return isinstance(x, (Array, np.ndarray)) and getattr(x, 'ndim', -1) == 0","tryCatchPattern":"try:\n    for v in maybe_scalar:\n        process(v)\nexcept TypeError as e:\n    if 'iteration over a 0-d array' in str(e):\n        process(maybe_scalar.item())\n    else:\n        raise","preventionTips":["Normalize inputs with jnp.atleast_1d before generic iteration","Convert scalars with .item() immediately after reductions like jnp.mean/jnp.sum","Keep APIs explicit about rank: document whether a function takes scalars or arrays"],"tags":["jax","numpy-interop","iteration","scalar","typeerror"],"backgroundTag":"iteration-over-scalar-array","analyzedSha":"1e1c6a8fc06dfcd1247076ec5cae4640cea5d7bb","analyzedAt":"2026-08-27T09:53:25.647Z","schemaVersion":2},"datasetVersion":"2026-08-27T13:17:12.746Z"}