Best way to have a for-loop index?

nikie n.estner at gmx.de
Wed Apr 5 17:10:04 EDT 2006


Roy Smith wrote:

> In article <1141950744.482666.4430 at j33g2000cwa.googlegroups.com>,
>  andrewfelch at gmail.com wrote:
>
> > I write a lot of code that looks like this:
> >
> > for myElement, elementIndex in zip( elementList,
> > range(len(elementList))):
> >     print "myElement ", myElement, " at index: ",elementIndex
> >
> >
> > My question is, is there a better, cleaner, or easier way to get at the
> > element in a list AND the index of a loop than this?
> >
> > TIA,
> > Andrew
>
> The real question is *why* do you want the index?
>
> If you're trying to iterate through list indicies, you're probably trying
> to write C, C++, Fortran, Java, etc in Python.

Interesting. I just wrote some tools today that parse through a bunch
of logfiles and print out something like: "unmatched memory allocation
in line XXX", or something like that. All of them have a main loop like
this:
  for lineNumber, line in enumerate(file("some.log")): ...
I don't think there's anything wrong with that, is there a better way
to do it?
Personally, I don't think "enumerate" would be there if it always
encouraged an "unpythonic" programming style. But then again, I'm not
dutch, so I couldn't tell... ;-)




More information about the Python-list mailing list