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

Fredrik Lundh fredrik at pythonware.com
Wed Nov 7 02:30:17 EST 2001


David Bolen wrote:
> > > | for i in range(len(my_list)):
> > > |     print i,". ",my_list[i]
> >
> > > What about the following ?
> > >
> > >    idx=0
> > >    for s in my_list:
> > >        print idx,".",s
> > >        idx+=1
>
> I'm not sure there's that much of a difference in this case

the former is about 10% faster, in most typical cases.

> but the second form is arguably more readable since the primary
> function (iterating over the list) is more clearly stated, and the
> use of the index variable is clear.

which is exactly why I prefer to use the latter myself.

(but usually spell it out as "idx=idx+1", which isn't only faster, but
also runs under 1.5.2)

</F>





More information about the Python-list mailing list