pythonscipyslicescipy-optimize

Error when using scipy brute: object of type 'slice' has no len()


I am posting this question-answer since this detail was subtle and I only happened on the solution because of a particular way somebody defined their slice object in a Stack Overflow answer that might not come up if someone searches for this particular error.

My original code:

from scipy.optimize import brute

f = lambda x : x
ranges = ( slice(-10,10,1) )
result = brute( f, ranges, full_output=True, finish=optimize.fmin )
print( result[1] )

The error, as in the title of the question:

TypeError: object of type 'slice' has no len()

The new code simply contains one more comma in the tuple defining ranges

from scipy.optimize import brute

f = lambda x : x
ranges = ( slice(-10,10,1), )
result = brute( f, ranges, full_output=True, finish=optimize.fmin )
print( result[1] )

The output:

-6.33825300114115e+29

And the answer to why the output was much less than -10 is answered in a different Stack Overflow post.


Solution

  • As stated in the question, the working code requires a comma after slice(-10,10,1).

    from scipy.optimize import brute
    
    f = lambda x : x
    ranges = ( slice(-10,10,1), )
    result = brute( f, ranges, full_output=True, finish=optimize.fmin )
    print( result[1] )