Function to determine list max without itertools

Ben Bacarisse ben.usenet at bsb.me.uk
Fri Apr 19 08:27:50 EDT 2019


Sayth Renshaw <flebber.crue at gmail.com> writes:

>> Now, what happens when the code is tested with various (different) sets 
>> of test-data?
>> (remember the last question from my previous msg!?)
>> 
> It fails on any list entry that isn't a float or an int, giving a TypeError.
>
>> Once you are happy with the various test-runs, do you have any ideas for 
>> making the code more efficient?
>> -- 
>> Regards =dn
>
> Efficient No, but resistant to error I can buy using try except to
> pass through TypeErrors.
>
> def max_try(listarg):
>     myMax = listarg[0]
>     try:
>         for item in listarg:
>             if item > myMax:
>                 myMax = item
>     except TypeError:
>         print(f'Only numbers are supported, this entry "{item}" was not')
>         pass
>
>     return myMax
>
> Thanks.

'pass' does not do what you think!  To re-raise the exception, use
'raise'.  'pass' is a null statement that does nothing.

But catching an exception just to print a message from a utility
function like this is not really a good idea.  It would be annoying to
many used of this function whilst adding little value over and above
what the traceback will show anyway.

There is another error case where you /could/ add a little value by
catching it in your function and raising a more appropriate exception.
What test cases have you used so far?

> PS Since I am going through the list fully the only optimisation I can
> think of a generator to feed it seems sort of redundant. Unless of
> course it was a list of 10,000 numbers then maybe its useful.

I'm not sure what was meant here.  I can think of one micro-optimisation
but I'd want to test to see if really makes and difference.

-- 
Ben.



More information about the Python-list mailing list