pola-rs/polars · error · TypeError
cannot set Series of dtype
Error message
cannot set Series of dtype: {self.dtype!r} with list/tuple as value; use a scalar value What it means
Series.__setitem__ raises this TypeError when the value being assigned is a list or tuple but the Series dtype is not one that supports sequence assignment. Polars only accepts scalar values (or matching structures like lists for list-dtype columns) when setting via a key; for this dtype you must use a scalar.
Solutions
- Assign a scalar: `series[mask] = 0` instead of a list
- Wrap the list in the appropriate structure only for List-dtype series (e.g. `series[i] = [1,2,3]` on List(Int64))
- Use `series.scatter(indices, value_series)` to set multiple positions from another Series
Example fix
// before s[s > 10] = [0, 0, 0] # TypeError // after s = pl.when(s > 10).then(0).otherwise(s)
Defensive patterns
Strategy: validation
Validate before calling
if isinstance(value, (list, tuple)) and not isinstance(series.dtype, pl.List):
raise ValueError("assign a scalar or use when/then instead of a list value")
series[mask] = value Type guard
def is_scalar(value: object) -> bool:
return not isinstance(value, (list, tuple, pl.Series)) Try / catch
try:
series[mask] = value
except TypeError as e:
if "list/tuple as value" in str(e):
series = pl.when(pl.Series([True] * len(series)) & mask).then(value[0]).otherwise(series)
else:
raise Prevention
- Assign scalars via __setitem__; use expressions (when/then) for vectorized replacement
- Use Series.scatter for multi-position assignment
- Don't copy numpy assignment idioms directly to polars Series
When it happens
Trigger: `series[mask_or_indices] = [1, 2, 3]` where series.dtype is e.g. Int32, Date, or another non-list dtype, hitting the branch at py-polars/src/polars/series/series.py:1433.
Common situations: Numpy habits (`arr[mask] = [..]`) carried into polars; assigning multiple replacement values at masked positions; pandas-style vectorized assignment of lists.
Understand the failure class
Background: "Must be a positive integer", "Invalid value", "Unsupported": the invalid-argument-value error family, when a library rejects the value you pass — this error's family across 35 libraries.
Related errors
- cannot use " " for indexing
- arr.to_struct() got a str instead of a list. hint: pass
- cannot call `map_groups` when filtering groups with `having`
- cannot call `map_groups` when grouping by an expression
- cannot call `map_groups` when grouping by named expressions
AI-assisted analysis of pola-rs/polars@fe841f959e (2026-09-18).
Data as JSON: /api/errors/d25b24eece7925ce.
Report an issue: GitHub.
Appendix: source
Thrown at py-polars/src/polars/series/series.py:1433
[
10
99
99
]
"""
# do the single idx as first branch as those are likely in a tight loop
if isinstance(key, int) and not isinstance(key, bool):
self.scatter(key, value)
return None
elif isinstance(value, Sequence) and not isinstance(value, str):
if self.dtype.is_numeric() or self.dtype.is_temporal():
self.scatter(key, value) # type: ignore[arg-type]
return None
msg = (
f"cannot set Series of dtype: {self.dtype!r} with list/tuple as value;"
" use a scalar value"
)
raise TypeError(msg)
if isinstance(key, Series):
if key.dtype == Boolean:
self._s = self.set(key, value)._s
elif key.dtype.is_integer():
self._s = self.scatter(key, value)._s
else:
msg = f"cannot use Series of dtype {key.dtype!r} for indexing; expected boolean or integer dtype"
raise TypeError(msg)
# TODO: implement for these types without casting to series
elif _check_for_numpy(key) and isinstance(key, np.ndarray):
if key.dtype == np.bool_:
# boolean numpy mask
self._s = self.scatter(np.argwhere(key)[:, 0], value)._s
else:
s = self._from_pyseries(
PySeries.new_u32("", np.array(key, np.uint32), _strict=True)
)View on GitHub (pinned to fe841f959e)