Skip to main content

9.6) Range, Len and the For Loop


You often use range() in combination with len() ; range(len(L)) will return a list of the indexes of the list L.

>>> L=[3,7,9]
>>> range(len(L))
[0, 1, 2]

Using len within a for loop, you can isolate the elements of one or more lists:

>>> S=['d','e','f']
>>> L=[4,5,6]
>>> for i in range(len(L)):
       print L[i],S[i]
4 d
5 e
6 f

Don’t overuse the range(len(L)) trick. If you only have one list, just directly loop over the list elements themselves:

for element in L:
    print element