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

MonkeeSage MonkeeSage at gmail.com
Sat Oct 7 01:15:10 EDT 2006



On Oct 6, 8:23 pm, Gabriel Genellina <gagsl... at yahoo.com.ar> 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. 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. And also why not the equivalent of dict.get for other
sequences:

def get(seq, index, default=None):
  if has_index(seq, index):
    return seq[index]
  else:
    return default

Seems useful...

Regards,
Jordan




More information about the Python-list mailing list