Lists and Indices

Bryan Olson fakeaddress at
Fri Aug 9 04:51:08 EDT 2002

Lindstrom Greg - glinds wrote:
 > I could do
 > for index in range(len(colors)):
 > 	print '%d.  %s' % ( index, colors[index])
 > but I don't like's not easily readable, IMHO.

The 'range(len(thing))' construct is so common in Python that just about
any Python programmer will be able to read it at a glance.  The loop
above is so small and self-contained that I wouldn't worry about it.
Some people define,

     def indices(sequence):
         return range(len(sequence))

which allows the arguably-more-readable,

     for index in indecies(colors):
         print '%d.  %s' % (index, colors[index])

We could also define the indices function using generators, which would
avoid building the whole list of indices,

     def indices(sequence):
         for i in range(len(sequence)):
             yield i

Unfortunately, there are two valid spellings of the plural of "index",
so we might also want,

     indexes = indices

Hmmm, I guess if you're that concerned about readability you wouldn't

print "\n".join(["%d\t%s" % (i, colors[i]) for i in range(len(colors))])


More information about the Python-list mailing list