Can't get around "IndexError: list index out of range"
MonkeeSage at gmail.com
Sat Oct 7 07:15:10 CEST 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):
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):
More information about the Python-list