can I get the index number in for x in y loop?

Felipe Almeida Lessa felipe.lessa at gmail.com
Mon Apr 3 12:08:42 EDT 2006


Em Seg, 2006-04-03 às 08:47 -0700, JuHui escreveu:
> which one has best performance?

Let's see...

> a:for i in range(0,len(a))

$ python2.4 -mtimeit -s 'a=[None]*100' 'for i in range(len(a)):
    j = a[i]
'
100000 loops, best of 3: 17.7 usec per loop

$ python2.4 -mtimeit -s 'a=[None]*100' 'for i in xrange(len(a)):
    j = a[i]
'
100000 loops, best of 3: 16.8 usec per loop

> b:for x in a

$ python2.4 -mtimeit -s 'a=[None]*100' 'i = 0
for j in a:
    i += 1
'
100000 loops, best of 3: 15.7 usec per loop

> c:for x,y in enumerate(a)

$ python2.4 -mtimeit -s 'a=[None]*100' 'for i, j in enumerate(a):
    pass
'
100000 loops, best of 3: 12.9 usec per loop


Using enumerate is cleaner and faster.

HTH,

-- 
Felipe.




More information about the Python-list mailing list