Counting the number of elements in a list - help.

Alex Martelli aleax at aleax.it
Thu Apr 18 16:23:00 EDT 2002


Christophe Delord wrote:
        ...
> It could be shorter and smarter like this :
> 
> def InRange(sequence, index):
>     return 0 <= index < len(sequence)

responding to:

>> > 2) a function which takes a list and an index and returns a zero when
>> > that list index is out of range.

No!  You're wrong.  -1 is in range for any non-empty list (it means the
last element), so why is your inRange function going to deny it?

FAR better Jeff Shannon's approach:

>> def InRange(sequence, index):
>>     try:
>>         sequence[index]
>>     except IndexError:
>>         return 0
>>     else:
>>         return 1

This lets *the sequence object* decide what indices are in or not-in
range.  By far the best approach.

If you insist that you know better than the object which indices are
in-range for it, at least use a body such as:

        thelen = len(sequence)
        return -thelen <= index < thelen

but no "checking" approach is going to be as complete and reliable
as try/except!


Alex
        



More information about the Python-list mailing list