[Tutor] len(l) as loop index

Jörg Wölke lumbricus@gmx.net
Fri, 5 Apr 2002 11:00:26 +0200 (MEST)


> Advice request:
> 
> 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 (e.g. n = len(list)) and then
> using n as the loop index:

But in your examples len(list) is _not_ the
loop index. It is just the maximum value of
the index i (!). And it is only computed once
(I think). So it is OK.
 
> list=[1,2,3]
> i=0
> while i<len(list):
> 	print list[i]
> 	i=i+1
> 
> or should we not even be using the while loop this, using the following
> instead:
> 
> for i in range(len(list)):
> 	print list[i]
> 
> or (if you don't need to know where you are):
> 
> for x in list:
> 	print x
> 
> The first method has been the method of choice for the How to Think text
> on Python for beginners.
> 
> /c

HTH, HAND and
Greetings, J"o!

-- 
$ make LOVE
Make: Don't know how to make LOVE.  Stop.
$ 

-- 
GMX - Die Kommunikationsplattform im Internet.
http://www.gmx.net