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

MonkeeSage MonkeeSage at gmail.com
Wed Oct 11 00:56:32 EDT 2006


On Oct 10, 1:57 am, Steve Holden <s... at holdenweb.com> wrote:
> I think we'll just have to agree to differ in this repsecrt, as I don't
> see your suggestions for extending the sequence API as particularly
> helpful.

No worries. :)


On Oct 10, 11:22 am, Fredrik Lundh <fred... at pythonware.com> wrote:
> so to "improve" a piece of code that's been optimized for the common
> case, you're adding an extra method call and a test to the inner loop?
>
> and this because you think Python programmers don't understand try-
> except statements ?

Uh, yeah, "You're all idiots and I'm not really a 'Python
Programmer'(TM)" -- that's exactly what I was meaning to say. I'm
suprised your telepathic powers let you pick up on that, since I didn't
say anything that could even remotely be construed that way. Freaky.

And, FWIW, the "optimized" version is not much faster than that put
forth by the stupid peon (me), even when my suggestion is implemented
in pure python:

$ cat test.py
import timeit
ary = ['blah'] * 10

def has_index(seq, idx):
  return idx < len(seq)
def at(seq, idx):
  if has_index(seq, idx):
    return seq[idx]

def t1():
  while 1:
    try:
      for i in range(11):
        ary[i]
    except IndexError:
      break
def t2():
  go = True
  while go:
    for i in range(11):
      if has_index(ary, i):
        ary[i]
      else:
        go = False
def t3():
  go = True
  while go:
    for i in range(11):
      val = at(ary, i)
      if val:
        val
      else:
        go = False

print 't1 time:'
print timeit.Timer('t1()', 'from __main__ import t1').timeit()
print 't2 time:'
print timeit.Timer('t2()', 'from __main__ import t2').timeit()
print 't3 time:'
print timeit.Timer('t3()', 'from __main__ import t3').timeit()

$ python test.py
t1 time:
15.9402189255
t2 time:
18.6002299786
t3 time:
23.2494211197

> I think we can all safely ignore you now.

You could have done that all along. I'm no Max Planck, and this isn't
quantum mechanics. But more interesting than whether it's "safe" to
ignore suggestions for improvement is whether its actually beneficial
to do so.


On Oct 10, 11:35 am, Fredrik Lundh <fred... at pythonware.com> wrote:
> > *) insert martelli essay here.for example:
>
> http://mail.python.org/pipermail/python-list/2003-May/163820.html

I don't think this is strictly a question of EAFP vs. LBYL, but more a
question of convenience. This very moment in python I can say both
"try: d[k] ..." and "if d.has_key[k] / k in d".

Regards,
Jordan




More information about the Python-list mailing list