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

Liam Clarke cyresse at gmail.com
Tue Nov 30 12:05:48 CET 2004


Oh, -1 is the index of the last element?



On Tue, 30 Nov 2004 05:48:43 -0500, Kent Johnson <kent37 at tds.net> wrote:
> 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
> _______________________________________________
> 
> 
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.


More information about the Tutor mailing list