count in 'for ... in ...'

DeVerter at robinsonmechanical.com DeVerter at robinsonmechanical.com
Fri Nov 9 23:37:01 CET 2001


Try this.

for s in my_list:
     print my_list.index(s), ".", s

This way you don't need a counter variable.

Mark d.




                                                                                                                       
                    "Achim Domma"                                                                                      
                    <achim.domma at syynx       To:     python-list at python.org                                            
                    .de>                     cc:                                                                       
                    Sent by:                 Subject:     count in 'for ... in ...'                                    
                    python-list-admin@                                                                                 
                    python.org                                                                                         
                                                                                                                       
                                                                                                                       
                    11/06/01 08:50 AM                                                                                  
                                                                                                                       
                                                                                                                       




Hi,

if I have a list of strings and want to display with a count in front of it
I usualy do something like:

for i in range(len(my_list)):
    print i,". ",my_list[i]

but I think the

for s in my_list:
    print ...

Syntax is much cleaner, because it clearly says what I'm doing. So I asked
myself : is there a way to get the internal count in 'for ...in' ? Of
course
it would be the same as the first version, but in my opinion it would fit
perfectly in the 'python-way' to say what one is doing.

greetings
Achim


--
http://mail.python.org/mailman/listinfo/python-list








More information about the Python-list mailing list