Which Python object(s) can be indexed/sliced with multiple entries in square brackets?

Question:

I am playing with Python and found a script online which contains a function. I wrote a simple analogous example below:

def func(thing):
    test = thing[0,:]
    print(test)

I do not know what datatype the variable "thing" is in this case. What kind of Python datatype/object can be called with square brackets like this?

If you run (using my example above) the variable "thing" as an np.array, dict or list, I get the error: "list indices must be integers or slices, not tuple"

Asked By: 13deadfrogs

||

Answers:

I do not know what datatype the variable "thing" is in this case. What kind of Python datatype/object can be called with square brackets like this?

Any object that has a __getitem__ method can be subscripted.

thing[0, :]

is simply syntactic sugar for

thing.__getitem__((0, slice(None, None, None)))

So, it is up to that object whether it wants to accept one, two, three, four, or however many parameters and whether it wants to accept certain types of parameters.

For example, the following can generate the error message you posted:

class Foo:
  def __getitem__(self, x):
    if not isinstance(x, (int, slice)):
      raise TypeError(f"list indices must be integers or slices, not {type(x)}")

foo = Foo()

foo[0, :]

The reason for the somewhat cryptic error is that multiple indices are desugared into a tuple. So, a __getitem__ which only expects a single parameter will be passed a tuple argument.

Answered By: Jörg W Mittag
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.