pola-rs/polars · error · TypeError

cannot select elements using Sequence with elements of type

Error message

cannot select elements using Sequence with elements of type {qualified_type_name(first)!r}

What it means

Series.__getitem__ accepts slices, int, Sequences of integers, pl.Series, and NumPy arrays. For a Sequence, polars builds pl.Series("", key, dtype=Int64); if the first element's type makes that fail (strings, floats, None, mixed), the TypeError is re-raised with this message naming the offending element type.

Source

Thrown at py-polars/src/polars/_utils/getitem.py:76

        return _select_elements_by_slice(s, key)

    elif isinstance(key, range):
        key = range_to_slice(key)
        return _select_elements_by_slice(s, key)

    elif isinstance(key, Sequence):
        if not key:
            return s.clear()

        first = key[0]
        if isinstance(first, bool):
            _raise_on_boolean_mask()

        try:
            indices = pl.Series("", key, dtype=Int64)
        except TypeError:
            msg = f"cannot select elements using Sequence with elements of type {qualified_type_name(first)!r}"
            raise TypeError(msg) from None

        indices = _convert_series_to_indices(indices, s.len())
        return _select_elements_by_index(s, indices)

    elif isinstance(key, pl.Series):
        indices = _convert_series_to_indices(key, s.len())
        return _select_elements_by_index(s, indices)

    elif _check_for_numpy(key) and isinstance(key, np.ndarray):
        indices = _convert_np_ndarray_to_indices(key, s.len())
        return _select_elements_by_index(s, indices)

    msg = f"cannot select elements using key of type {qualified_type_name(key)!r}: {key!r}"
    raise TypeError(msg)


def _select_elements_by_slice(s: Series, key: slice) -> Series:
    return PolarsSlice(s).apply(key)  # type: ignore[return-value]

View on GitHub (pinned to df599052da)

Solutions

  1. Use integer indices for positional selection: s[[0, 1]].
  2. Coerce numeric keys: [int(i) for i in key] when they are whole numbers.
  3. For name/value-based selection on a Series, use a Boolean mask: s[s.is_in(["a", "b"])].

Example fix

// before
rows = s[["a", "b"]]  # Series, not DataFrame

// after
rows = s[s.is_in(["a", "b"])]  # boolean mask by value
Defensive patterns

Strategy: type-guard

Validate before calling

if isinstance(key, (list, tuple)) and key and not all(isinstance(i, int) and not isinstance(i, bool) for i in key):
    if all(isinstance(i, float) and i.is_integer() for i in key):
        key = [int(i) for i in key]
    else:
        raise TypeError(f"Series indexing needs int indices, got {type(key[0]).__name__}")
rows = s[list(key)]

Type guard

def is_int_index_sequence(key: Sequence) -> bool:
    return bool(key) and all(
        isinstance(i, int) and not isinstance(i, bool) for i in key
    )

Try / catch

try:
    rows = s[key]
except TypeError as e:
    if "cannot select elements using Sequence" in str(e):
        rows = s[s.is_in(list(key))]  # fall back to value-based mask
    else:
        raise

Prevention

When it happens

Trigger: s[["a", "b"]] (name-based indexing is not supported on Series); s[[0.0, 1.0]]; s[[None, 1]]; indices decoded from JSON as strings or floats.

Common situations: Reusing DataFrame-style df[["a","b"]] syntax on a Series; index lists loaded from JSON/config arriving as strings or floats; numpy operations returning float indices.

Related errors


AI-assisted analysis of pola-rs/polars@df599052da (2026-08-16). Data as JSON: /api/errors/c3b483410dd71306. Report an issue: GitHub.