Testing validity of for...in...
Peter Otten
__peter__ at web.de
Mon Nov 3 08:04:48 EST 2003
Richard Philips wrote:
> def maxlength(mylist):
> assert isinstance(mylist, list), "A list with strings"
> max = -1
for item in mylist:
> if len(item)>max:
> max = len(item)
> return max
Your implementation makes two implicit tests:
1. Is mylist iterable
2. Do the items in mylist have a length
There is no point in duplicating these tests. On the other hand, if you
really want to accept only strings as items, you should put
assert isinstance(item, basestring), "Sequence item must be a string"
into the for loop. I'm not advocating that because it unnecessarily limits
the generality of the algorithm.
Other unrelated observations:
max is a built-in function, don't use it as a variable name.
-1 is not a length, if you don't want to accept empty lists/sequences, raise
an exception when you encounter one, otherwise return 0.
OK, the last one is only a personal preference...
Peter
More information about the Python-list
mailing list