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

Gabriel Genellina gagsl-py at
Sat Oct 7 10:27:16 CEST 2006

At Saturday 7/10/2006 02:15, MonkeeSage wrote:

>On Oct 6, 8:23 pm, Gabriel Genellina <gagsl... at> wrote:
> > if 2 in [1,2,3]: print "Use the same (in) operator"
> > elif 'E' in ('E','r','i','k'): print "Works for any sequence"
> > elif 'o' in 'hello': print "Even strings"
>This isn't really analogous is it? For "somedict.has_key(k)" or "k in
>somedict", you don't need to know the value of somedict[k] ahead of
>time. So you can avoid KeyError by asking if the key exists first
>before trying to get the value.

The meaning comes from the most common usage. For a list, you want to 
know if an object is contained in the list (not if an index is in 
range!). For a dictionary, you usually want to know if it maps 
anything to a given key (not if any key maps to that value!). These 
are the most common operations, and that's why they have the simple 
sintax "a in b". [BTW, usage of operator "in" as "key in dict" is 
rather new to Python; has_key() were the only way to test for key 
existence some time ago].

>Wouldn't that be more like this for
>lists (and other sequences):
>def has_index(seq, index):
>   try:
>     seq[index]
>     return True
>   except IndexError:
>     return False
>I've often wondered why there is no built-in method like that for
>sequence objects.

Because it's not needed at all: valid sequence indexes are *exactly* 
range(len(seq)). This is the basic point of being a sequence: when 
indexes are not contiguous, in fact you have a mapping, not a sequence.

>And also why not the equivalent of dict.get for other
>def get(seq, index, default=None):
>   if has_index(seq, index):
>     return seq[index]
>   else:
>     return default
>Seems useful...

Sometimes, maybe... But since you can write it efficientely in a few 
lines when needed, I don't see the need to put it into the core language.

Gabriel Genellina
Softlab SRL 

Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!

More information about the Python-list mailing list