PEP 276 Simple Iterator for ints

James_Althoff at i2.com James_Althoff at i2.com
Thu Nov 29 20:41:18 CET 2001


Bjorn Pettersen wrote:
>> From: Kerim Borchaev [mailto:warkid at storm.ru]
>>
>> Hello James,
>> Thursday, November 29, 2001, 5:18:43 AM, you wrote:
>> Jic> Peter Hansen wrote:
>> >>Or just:
>> >>
>> >>if not 0 <= index < len(mylist):
>> >>    print 'index out of range'
>>
>> Jic> Right.  Which has the added advantage of not repeating index.
>>
>> Why not just _use_ that index on the list to check whether it's valid?
>>
>> try:
>>     mylist[index]
>> except IndexError:
>>     print 'index out of range'
>
>Because a negative index doesn't give an IndexError, and presumably we
>wanted to make sure the list was accessed through a positive index...
>
>-- bjorn

Exactly.

Python's builtin Lists and Tuples are conveniently designed to allow
negative indexing.  But DefaultTableModel in Jython, for example, can only
be accessed using *positive* indicies.  You *could* use the exception
mechanism with DefaultTableModel, but it isn't quite so convenient, e.g.,

    from java.lang import ArrayIndexOutOfBoundsException
    try:
        value = table.getValueAt(i,j)
    except ArraryIndexOutOfBoundsException:
        print 'invalid index'

And with this approach we don't know which index, i or j, is invalid
(without doing even more work).  So there can be cases where one prefers to
do a bounds check ahead of time.

Jim






More information about the Python-list mailing list