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

MonkeeSage MonkeeSage at
Sat Oct 7 07:15:10 CEST 2006

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. Wouldn't that be more like this for
lists (and other sequences):

def has_index(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

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

Seems useful...


More information about the Python-list mailing list