[Tutor] when do I use this?

Alan Gauld alan.gauld at blueyonder.co.uk
Tue Mar 16 03:55:03 EST 2004


> Several times I have iterated over a sequence with
> some code that looks like this:
> 
> for f in range(len(files)):
> 
> and fellow hackers have told me I can just use:
> 
> for f in seq:


That's right. If you have a collection of items there is no 
point in you calculating the length of the collection then 
manually extracting each item within your for loop when python 
will hand you the item directly.

So if you want to process all the items in a collection use

for item in collection:
    doit(item)

instead of

for index in range(len(collection)):
    item = collection[index]
    doit(item)

It's less error prone and a lot shorter to type!

Alan G.





More information about the Tutor mailing list