Can't get around "IndexError: list index out of range"

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Sat Oct 7 20:59:06 EDT 2006


On Sat, 07 Oct 2006 17:25:15 -0700, MonkeeSage wrote:

> My point wasn't in regard to implementation details, but in regard to
> convenience methods. Obviously the sugary dict methods are tweaked for
> the best performance (one would hope!), as would be sugary sequence
> methods were they to be added. What I was wondering is why
> dict.has_key() and get() are there but not list.has_index() and get().

Because they aren't needed often, and when they are, they are easy to
implement?

Instead of list.has_index(n), write 0 <= n < len(list).

If you want to allow for negative indices as well, write
-len(list) <= n < len(list).


It is hard to see where list.get(index, default) would be useful, since
accessing an index out of range of a list is generally an error, unlike
accessing a missing key. But I like symmetry, and for symmetry I wouldn't
object to sequences gaining a get method too. Not that I care about it
enough to put in a feature request or a PEP, but if somebody else did, I
wouldn't object.

(Note, though, that accessing a *slice* out of range is not an error, but
returns an empty list.)

get() is easy enough to implement. Feel free to turn it into a method
of a collection class if you like.

def get(mapping_or_sequence, key_or_index, default=None):
    try:
        return mapping_or_sequence.get(key_or_index, default)
    except AttributeError:
        # probably a sequence
        try:
            return mapping_or_sequence[key_or_index]
        except IndexError:
            return default

Not every piece of functionality needs to be a built-in. 


-- 
Steven.




More information about the Python-list mailing list