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

Kent Johnson kent37 at tds.net
Tue Nov 30 13:36:22 CET 2004


Yes, any negative indices are counted from the end. One way to remember 
is to think of s[-x] as a shorthand for s[len(s)-x].

You can use negative indices in slices, too:
 >>> s='hello
 >>> s[-1]
'o'
 >>> s[-2]
'l'
 >>> s[1:-1]
'ell'
 >>> s[-3:-1]
'll'

Kent


Liam Clarke wrote:
> 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
>>
> 
> 
> 


More information about the Tutor mailing list