[Tutor] len(l) as loop index

Christopher Smith csmith@blakeschool.org
Thu, 04 Apr 2002 16:15:38 -0600


alan.gauld@bt.com writes:
>> Since the calculation of the list length is probably such a 
>> small part of any task you are doing, is there any problem 
>> with using len(list) as a loop index as opposed to 
>> calculating it once 
>
>That's a big assumption! A len() query basically has to 
>run alomng the list counting members. If its a big list
>that could take far more time than processing the loop body.

Are you sure?  That's what I thought but then I thought the length
parameter might actually be something that Python stores with its info
about the object so it might not actually take too long--it essentially
just finds out what the stored len parameter is for the object.  I tried
the following runs for which the first took 8 seconds and the second took
11 seconds.  So the index access time is about 50% longer but is a really
small time.

it=3000000
l=range(100000)
n=len(l)

import my
t=my.start()
i=0
while i<it:
	n
	i+=1
print my.stop(t)

t=my.start()
i=0
while i<it:
	len(l)
	i+=1
print my.stop(t)

/c