{"record":{"id":"393610b54f743394","repo":"pandas-dev/pandas","slug":"key-must-be-an-int-or-slice-got-type-key-name","errorCode":null,"errorMessage":"key must be an int or slice, got {type(key).__name__}","messagePattern":"key must be an int or slice, got (.+?)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/arrow/accessors.py","lineNumber":195,"sourceCode":"            # TODO: Support negative start/stop/step, ideally this would be added\n            # upstream in pyarrow.\n            start, stop, step = key.start, key.stop, key.step\n            if start is None:\n                # TODO: When adding negative step support\n                #  this should be set to last element of array\n                # when step is negative.\n                start = 0\n            if step is None:\n                step = 1\n            sliced = pc.list_slice(self._pa_array, start, stop, step)\n            return Series(\n                sliced,\n                dtype=ArrowDtype(sliced.type),\n                index=self._data.index,\n                name=self._data.name,\n            )\n        else:\n            raise ValueError(f\"key must be an int or slice, got {type(key).__name__}\")\n\n    def __iter__(self) -> Iterator:\n        raise TypeError(f\"'{type(self).__name__}' object is not iterable\")\n\n    def flatten(self) -> Series:\n        \"\"\"\n        Flatten list values.\n\n        Each list element is expanded into separate rows, preserving the\n        original index. The resulting Series may have a longer length than\n        the original if lists contain more than one element.\n\n        Returns\n        -------\n        pandas.Series\n            The data from all lists in the series flattened.\n\n        See Also","sourceCodeStart":177,"sourceCodeEnd":213,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/arrow/accessors.py#L177-L213","documentation":"`ValueError('key must be an int or slice, got {type}')` from `ListAccessor.__getitem__`. The accessor only accepts an `int` (positional list index, forwarded to `pc.list_element`) or a `slice` (forwarded to `pc.list_slice`). Anything else — a string field name, a list of indices, a numpy array, a tuple — falls through to the `else` and raises. Note negative int is not yet supported (pyarrow limitation called out in the code).","triggerScenarios":"`s.list['name']` (string), `s.list[[0,1]]` (list), `s.list[1:3:2]` works but `s.list[-1]` is unsupported, `s.list[arr]` (numpy array), `s.list[(0,1)]` (tuple).","commonSituations":"Confusing the list accessor with the struct accessor (`.list` indexes positions, `.struct.field` indexes names); trying fancy indexing; assuming negative indexing works as it does on Python lists.","solutions":["Use an int for a single position: `s.list[0]`.","Use a slice for a sub-range: `s.list[0:2]`.","For per-row variable indices, build an integer pyarrow array and use `pc.list_element` directly, or `explode`+filter.","If you meant a named field, switch to `.struct.field(name)` on a struct-dtype Series."],"exampleFix":"// before\ns.list[[0, 1]]            # list key -> ValueError\ns.list['first']           # str key -> ValueError\n\n// after\ns.list[0:2]               # slice\n# per-row indices:\nidx = pa.array([0,1,0])\npd.Series(pa.compute.list_element(s.array._pa_array, idx), index=s.index)","handlingStrategy":"type-guard","validationCode":"if not isinstance(key, (int, slice)):\n    raise TypeError(f'list accessor key must be int or slice, got {type(key).__name__}')\ns.list[key]","typeGuard":"def is_valid_list_key(key) -> bool:\n    return isinstance(key, (int, slice)) and not (isinstance(key, int) and key < 0)","tryCatchPattern":"try:\n    out = s.list[key]\nexcept ValueError as e:\n    if 'key must be an int or slice' in str(e):\n        raise TypeError('Use .list[int] or .list[slice]; for names use .struct.field') from e\n    raise","preventionTips":["Remember .list indexes positions only (int/slice); .struct.field indexes names","Avoid negative ints - not yet supported"],"tags":["accessor","list","indexing","pyarrow"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}