[Tutor] len(l) as loop index

alan.gauld@bt.com alan.gauld@bt.com
Fri, 5 Apr 2002 10:56:35 +0100


> >That's a big assumption! A len() query basically has to 
> >run alomng the list counting members. 
> 
> 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

I guess a test will prove it...

#-------------
import time
#create lists outside loop to avoid slewing results
Lists = [range(10), range(10000), range(10000000)]

start = time.time()

for i in [0,1,2]:
    len(Lists[i]) # use different length lists

mid = time.time()

for i in [0,1,2]:
    len(Lists[0]) # use same length list each time

stop = time.time()
print mid-start
print stop-mid
#-----------------

Yields
0.05
0.0

So it looks from this test that len() is dependant 
to some degree on length of list.
But if thats true then by using Lists[2] in the 
second loop I should get the second figure being 
bigger, in fact I get:
0.05
0.0

Exactly the same! Oh well,  I guess we need to 
go read the source... ;-)

Anyone else checked the source while I've been wasting 
my time?

Alan g.