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

Fredrik Lundh fredrik at pythonware.com
Tue Oct 10 18:33:02 CEST 2006


Terry Reedy wrote:

> Is there an outer loop being 'break'ed?

yes.

> This break is swallowed by the for loop, so not exactly equivalent, I 
> think.

the code is supposed to break out of the outer loop when it runs out of 
lines, so yes, monkeeboy's code is broken in more than one way.

> In any case, these are both clumsy and I believe I would instead 
> write something like
> 
> for i in range(lineno, len(self.__lines)):
>   print self.__lines[i]

that doesn't do the same thing, either.

and you both seem to be missing that

     try:
         for loop over something:
             do something with something
     except IndexError:
         ...

is a common pydiom when you expect to process quite a few somethings, 
and you don't want to waste time on calculating end conditions up front 
or checking for end conditions inside the loop or otherwise looking 
before you leap (LBYL); the pydiom lets you process things as quickly as 
you possibly can, as long as you possibly can, and deal with the end of 
the sequence when you hit it (EAFP*).

</F>

*) insert martelli essay here




More information about the Python-list mailing list