Lists and Indices

Bryan Olson fakeaddress at nowhere.org
Fri Aug 9 10:51:08 CEST 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 that..it'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
like,

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


--Bryan




More information about the Python-list mailing list