pola-rs/polars · error · TypeError
cannot convert List dtype to Tensor (use Array dtype…
Error message
cannot convert List dtype to Tensor (use Array dtype instead)
What it means
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.
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
Example fix
// before srs.to_torch() # srs.dtype == pl.List // after srs.list.eval(...).cast(pl.Array(pl.Float32, shape)).to_torch()
Defensive patterns
Strategy: type-guard
Validate before calling
if isinstance(srs.dtype, pl.List):
srs = srs.cast(pl.Array(srs.dtype.inner, srs.dtype.size if hasattr(srs.dtype, 'size') else width)) Type guard
def is_tensor_convertible(srs: pl.Series) -> bool:
return not isinstance(srs.dtype, pl.List) Try / catch
try:
t = srs.to_torch()
except TypeError as e:
if 'List dtype' in str(e):
t = srs.list.len().max() # determine width, cast to Array first
else:
raise Prevention
- Use pl.Array (fixed width) for tensor-bound columns
- Normalize ragged lists to fixed length before conversion
- Check srs.dtype before calling to_torch
When it happens
Trigger: srs.to_torch() on a Series whose dtype is pl.List(...) (variable-length lists), e.g. data from .list.* operations or JSON arrays.
Common situations: Converting nested list columns parsed from JSON to tensors; forgetting to convert variable-length lists to fixed-size pl.Array before tensor conversion.
Related errors
- cannot initialize Series from DataFrame without any columns
- conversion of polars data type
- dimensions of columns arg must match data dimensions
- expected data of type Sequence, got
- Pandas dataframe contains non-unique indices and/or column…
AI-assisted analysis of pola-rs/polars@fe841f959e (2026-09-18).
Data as JSON: /api/errors/0d284de271bddf1b.
Report an issue: GitHub.
Appendix: source
Thrown at py-polars/src/polars/series/series.py:5186
torch = import_optional("torch")
# PyTorch tensors do not support uint16/32/64
if self.dtype in (UInt32, UInt64):
srs = self.cast(Int64)
elif self.dtype == UInt16:
srs = self.cast(Int32)
else:
srs = self
# we have to build the tensor from a writable array or PyTorch will complain
# about it (writing to a readonly array results in undefined behavior)
numpy_array = srs.to_numpy(writable=True)
try:
tensor = torch.from_numpy(numpy_array)
except TypeError:
if self.dtype == List:
msg = "cannot convert List dtype to Tensor (use Array dtype instead)"
raise TypeError(msg) from None
raise
# note: named tensors are currently experimental
# tensor.rename(self.name)
return tensor
@removed_parameters(
RenamedParameter(
name="future",
new_name="compat_level",
deprecated_in="1.1",
removed_in="2.0",
),
)
def to_arrow(self, *, compat_level: CompatLevel | None = None) -> pa.Array:
"""
Return the underlying Arrow array.
If the Series contains only a single chunk this operation is zero copy.View on GitHub (pinned to fe841f959e)