Index () Method Do Not Accept None as Start / Stop

When writing a binary search method for a list, I decided to use the inline method index()

on a smaller chunk of the list that is determined by the binary search method. However, in some cases I was getting the error:

TypeError: slice indices must be integers or None or have an __index__ method

      

This happened when the list was below a certain length. The code that caused this:

def iter_chop(target, a_list):
    arr = a_list[:]
    start = None
    stop = None
    <snip>
    return a_list.index(target, start, stop)

      

Where start

and stop

where are both None

.

The error message indicates what None

is an acceptable parameter and it should be like this valid Python:

>>> a = [1,2,3,4,5]
>>> a[None:None]
[1, 2, 3, 4, 5]

      

So I assumed that calling a.index(3, None, None)

would be equivalent to calling a[None:None].index(3)

. However:

>>> a.index(3,None,None)
Traceback (most recent call last):
  File "<pyshell#199>", line 1, in <module>
    a.index(3,None,None)
TypeError: slice indices must be integers or None or have an __index__ method

      

I mistakenly assumed how the parameters for are handled index()

despite what the error message indicates? This is mistake?

+3


source to share


1 answer


This is a mistake in the way arguments are parsed. See issue # 1259 and issue # 11828 for the same error with string methods and issue # 13340 for lists.

Yes, the documentation assumes that indexes are used in much the same way as a slice, and an internal utility function used to parse those arguments results in an erroneous error message.



The error in the list appears to hang when the API changes and which versions will get the fix, or alternatively if the error message should be corrected instead.

+3


source







All Articles