[Tutor] len(l) as loop index
alan.gauld@bt.com
alan.gauld@bt.com
Thu, 4 Apr 2002 17:04:18 +0100
> 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.
A quick test:
import time
L = range(100000000) # 1 million ints
start = time.time()
l = len(L)
j = 0
while j < l:
if L[j] % 10000000 == 0: # every 100K
print j
j += 1
stop = time.time
print stop-start
vv
import time
L = range(100000000) # 100 million ints
start = time.time()
j = 0
while j < len(L):
if L[j] % 10000000 == 0: # every 10 million
print j
j += 1
stop = time.time
print stop-start
Gives me times of 3.5 for the 1st and 5.8 for the second
- the first is about 60% faster
Obviously if you are doing a lot of processing in the
loop body the difference becomes minimal. But the extra
code is minimal why not just be as fast as you can be?
> for i in range(len(list)):
> print list[i]
This is a waste of space and time IMHO.
Using an index in a for loop is of little use
since you can't modify the list without damage
anyway
> for x in list:
> print x
This is shorter and faster.
(Using the above loop I get 2.75 for this one
- half of the longest value)
You only need the while loop if you intend to add/delete
items and even then you need to be careful to maintain
the index correctly - and in this case having len()
inside the loop is probably the right way to go!.
Alan g.