pola-rs/polars · error · TypeError

`indices` is not a sequence

Error message

`indices` is not a sequence

What it means

Raised by PolarsDataFrame.select_columns when the indices argument is not a collections.abc.Sequence — e.g. a single int, an iterator/generator, a set, or a numpy array. The interchange method indexes columns positionally and requires a genuine Sequence (list, tuple, range, ...).

Source

Thrown at py-polars/src/polars/interchange/dataframe.py:138

        return PolarsColumn(s, allow_copy=self._allow_copy)

    def get_columns(self) -> Iterator[PolarsColumn]:
        """Return an iterator yielding the columns."""
        for column in self._df.get_columns():
            yield PolarsColumn(column, allow_copy=self._allow_copy)

    def select_columns(self, indices: Sequence[int]) -> PolarsDataFrame:
        """
        Create a new dataframe by selecting a subset of columns by index.

        Parameters
        ----------
        indices
            Column indices
        """
        if not isinstance(indices, Sequence):
            msg = "`indices` is not a sequence"
            raise TypeError(msg)
        if not isinstance(indices, list):
            indices = list(indices)

        return PolarsDataFrame(
            self._df[:, indices],
            allow_copy=self._allow_copy,
        )

    def select_columns_by_name(self, names: Sequence[str]) -> PolarsDataFrame:
        """
        Create a new dataframe by selecting a subset of columns by name.

        Parameters
        ----------
        names
            Column names.
        """
        if not isinstance(names, Sequence):

View on GitHub (pinned to df599052da)

Solutions

  1. Wrap in a list: select_columns(list(indices)) (or [indices] for a single int)
  2. Materialize generators before the call
  3. For numpy arrays, use .tolist()

Example fix

// before
df.__dataframe__().select_columns({0, 2})
// after
df.__dataframe__().select_columns([0, 2])
Defensive patterns

Strategy: type-guard

Validate before calling

from collections.abc import Sequence

if not isinstance(indices, Sequence):
    indices = [indices] if isinstance(indices, int) else list(indices)

Type guard

from collections.abc import Sequence

def is_sequence(obj) -> bool:
    return isinstance(obj, Sequence)

Try / catch

try:
    dfi = dfi.select_columns(indices)
except TypeError:
    dfi = dfi.select_columns(list(indices))

Prevention

When it happens

Trigger: select_columns(0) with a bare int; select_columns(iter([0, 1])) or a generator; select_columns({0, 2}) (set is not a Sequence); passing a numpy array of indices.

Common situations: Consumers deriving column subsets from set operations or generators; wrapping a single index because the caller usually wants one column; feeding numpy integer arrays straight through.

Related errors


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