{"record":{"id":"0d284de271bddf1b","repo":"pola-rs/polars","slug":"cannot-convert-list-dtype-to-tensor-use-array-dty","errorCode":null,"errorMessage":"cannot convert List dtype to Tensor (use Array dtype instead)","messagePattern":"cannot convert List dtype to Tensor \\(use Array dtype instead\\)","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/series/series.py","lineNumber":5186,"sourceCode":"        torch = import_optional(\"torch\")\n\n        # PyTorch tensors do not support uint16/32/64\n        if self.dtype in (UInt32, UInt64):\n            srs = self.cast(Int64)\n        elif self.dtype == UInt16:\n            srs = self.cast(Int32)\n        else:\n            srs = self\n\n        # we have to build the tensor from a writable array or PyTorch will complain\n        # about it (writing to a readonly array results in undefined behavior)\n        numpy_array = srs.to_numpy(writable=True)\n        try:\n            tensor = torch.from_numpy(numpy_array)\n        except TypeError:\n            if self.dtype == List:\n                msg = \"cannot convert List dtype to Tensor (use Array dtype instead)\"\n                raise TypeError(msg) from None\n            raise\n        # note: named tensors are currently experimental\n        # tensor.rename(self.name)\n        return tensor\n\n    @removed_parameters(\n        RenamedParameter(\n            name=\"future\",\n            new_name=\"compat_level\",\n            deprecated_in=\"1.1\",\n            removed_in=\"2.0\",\n        ),\n    )\n    def to_arrow(self, *, compat_level: CompatLevel | None = None) -> pa.Array:\n        \"\"\"\n        Return the underlying Arrow array.\n\n        If the Series contains only a single chunk this operation is zero copy.","sourceCodeStart":5168,"sourceCodeEnd":5204,"githubUrl":"https://github.com/pola-rs/polars/blob/fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e/py-polars/src/polars/series/series.py#L5168-L5204","documentation":"Series.to_torch builds a tensor via torch.from_numpy on the Series' numpy representation. Polars List dtypes cannot be represented as a regular numpy tensor; the underlying TypeError from torch is caught and re-raised with guidance to use the fixed-width Array dtype instead.","triggerScenarios":"srs.to_torch() on a Series whose dtype is pl.List(...) (variable-length lists), e.g. data from .list.* operations or JSON arrays.","commonSituations":"Converting nested list columns parsed from JSON to tensors; forgetting to convert variable-length lists to fixed-size pl.Array before tensor conversion.","solutions":["Use an Array dtype instead: srs.cast(pl.Array(pl.Int64, width))","Reshape data so each row has the same length, then cast to Array","Explode or flatten the list column before conversion"],"exampleFix":"// before\nsrs.to_torch()  # srs.dtype == pl.List\n// after\nsrs.list.eval(...).cast(pl.Array(pl.Float32, shape)).to_torch()","handlingStrategy":"type-guard","validationCode":"if isinstance(srs.dtype, pl.List):\n    srs = srs.cast(pl.Array(srs.dtype.inner, srs.dtype.size if hasattr(srs.dtype, 'size') else width))","typeGuard":"def is_tensor_convertible(srs: pl.Series) -> bool:\n    return not isinstance(srs.dtype, pl.List)","tryCatchPattern":"try:\n    t = srs.to_torch()\nexcept TypeError as e:\n    if 'List dtype' in str(e):\n        t = srs.list.len().max()  # determine width, cast to Array first\n    else:\n        raise","preventionTips":["Use pl.Array (fixed width) for tensor-bound columns","Normalize ragged lists to fixed length before conversion","Check srs.dtype before calling to_torch"],"tags":["polars","torch","list-dtype","tensor","conversion"],"backgroundTag":"unsupported-dtype","analyzedSha":"fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e","analyzedAt":"2026-09-18T22:14:11.667Z","contentChangedAt":"2026-09-18T22:14:11.667Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}