[Tutor] len(l) as loop index

Christopher Smith csmith@blakeschool.org
Thu, 04 Apr 2002 07:46:47 -0600


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:

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