[Tutor] design question -- nested loops considered harmful?

Kent Johnson kent37 at tds.net
Tue Nov 30 11:48:43 CET 2004


Liam Clarke wrote:
> x=file('Brian's source file') 'r')
> a=x.readlines() #How big is it? If it's a huge file, this may not be the best
> x.close()
> a="".join(a) #Turns a list into a string

a = x.read() is simpler

> If there are multiple occurrences, all you have to do is - 
> 
> for item in item_flags:
> 
>   foundIndice=[]
>   findIndex=0
>   startIndex=0
> 
>   while findIndex ! = -1:
>           findIndex=string2FindIn.find(item, startIndex)
>           foundIndice.append(findIndex)
>    
>   del foundIndice[len(foundIndice)-1] #Delete last item, as .find
> returns "-1" for string not
>                                                     #found, and this
> will always be appended at end.
>    data_dict[item]=foundIndice

I don't like this 'fix up the list after the loop' style. I would write 
it like this:

   index= -1
   while True:
         index=string2FindIn.find(item, index+1)
         if index== -1:
             break
         foundIndice.append(index)

Alternatively, foundIndice.pop() or del foundIndice[-1] is an easy way 
to remove the last element.

Kent


More information about the Tutor mailing list