[Tutor] Correct use of range function..

Kent Johnson kent37 at tds.net
Sun Jun 10 17:31:44 CEST 2007


David Hamilton wrote:
> I just finished doing an exercise in a tutorial on the range function 
> and while I got it to work, my answer seems ugly. I'm wondering if I'm 
> missing something in the way I'm using the range function.
> The tutorial ask me to print a string backwards. My solution works, but 
> it it just doesn't "feel" right :).  My result is difficult to read and 
> I feel like I'm probably over complicating the solution. Suggestions?
> 
> word="reverse"
> #Start at the end of the string, count back to the start, printing each 
> letter
> for  i in range(len(word)-1,-1,-1):
>     print word[i],

That's probably the best you can do using range(). You could write
ln = len(word)
for i in range(ln):
   print word[ln-i-1],

but that is not much different.

You can do better without using range; you can directly iterate the 
letters in reverse:

for c in word[::-1]:
   print c,

Kent


More information about the Tutor mailing list