Can't get around "IndexError: list index out of range"
Terry Reedy
tjreedy at udel.edu
Tue Oct 10 12:04:32 EDT 2006
"MonkeeSage" <MonkeeSage at gmail.com> wrote in message
news:1160455280.118212.202770 at b28g2000cwb.googlegroups.com...
> But even so, here is a simple use case from the standard library
> (python 2.5 release source):
>
> In Libs/site.py, lines 302-306:
>
> try:
> for i in range(lineno, lineno + self.MAXLINES):
> print self.__lines[i]
> except IndexError:
> break
Is there an outer loop being 'break'ed? If not, it should be pass instead.
> With my proposal, that could be written as:
>
> for i in range(lineno, lineno + self.MAXLINES):
> if self.__lines.has_index(i):
> print self.__lines[i]
> else:
> break
This break is swallowed by the for loop, so not exactly equivalent, I
think. 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]
or even better, use islice -- for line in islice(...): print line
So not a persuasive use case to me.
Terry Jan Reedy
More information about the Python-list
mailing list