Lists and Indices

dougfort dougfort at dougfort.net
Thu Aug 8 14:10:27 EDT 2002


Lindstrom Greg - glinds wrote:

> 
> Hi,
> 
> I would like to write out the (not necessarily unique) contents of a list
> with corresponding index numbers. Suppose I have
> 
> colors = ['red', 'green', 'blue', 'red']
> 
> and I want to see
> 
> 1.  red
> 2.  green
> 3.  blue

Here's one from O'Reilly's new 'Python Cookbook':

for index, color in zip(xrange(0, len(colors)), colors):
    print "%d. %s" % (index+1, color
> 4.  red
> 
> I currently use
> 
> index=1
> for color in colors:
>     print '%d.  %s' % (index, color)
>     index += 1
> 
> but that does not seem pretty to me; I don't like the "extra" lines
for the
> index variable.   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.
> 
> If the entries were unique, I believe this would be easy, but how can I do
> it with non-unique entries?
> 
> Thanks
> 
> Greg Lindstrom
> Acxiom Corporation,                    mail: CWY10011149
> InfoBase Products Development                  office: (501) 342-1626
> 301 Industrial Blvd, Conway, AR, 72032     fax:     (501) 336-3911 
> email: Greg.Lindstrom at acxiom.com           
> 
> We who cut mere stones must always be envisioning cathedrals. -- Quarry
> Worker's Creed
> 
> 
> 
> ********************************************************************
> 
> The information contained in this communication is
> confidential, is intended only for the use of the recipient
> named above, and may be legally privileged.
> If the reader of this message is not the intended
> recipient, you are hereby notified that any dissemination, 
> distribution, or copying of this communication is strictly
> prohibited.
> If you have received this communication in error,
> please re-send this communication to the sender and
> delete the original message or any copy of it from your
> computer system. Thank You.
> 
> 
> -- 
> <a
href="http://mail.dougfort.net//jump/http://mail.python.org/mailman/listinfo/python-list">http://mail.python.org/mailman/listinfo/python-list</a>

Doug Fort <dougfort at dougfort.net>
http://www.dougfort.net




More information about the Python-list mailing list