Countdown

Robert Kern kern at caltech.edu
Thu Jun 22 20:48:33 EDT 2000


Jeff Sandys wrote:
> 
> Python is really elegant when counting up:
> 
> for i in range(len(thing)):
>     print thing[i]
> 
> But when counting down looks ugly:
> 
> for j in range(len(thing)-1,-1,-1):
>     print thing[i]
> 
> Advice so far:
> Stop doing things backwards:
>     (customer request)
> Use reverse first:
>     (destructive, need to unreverse after)
> Live with it:
>     (bytecode doesn't care, but it is still ugly)
> Try range(len(thing)).reverse():
>     (doesn't work but):
>         rthing = range(len(thing))
>         rthing.reverse()
>         for k in rthing:
>             print thing[i]
>     (works, but also ugly)

So stick it in a function.

def revrange(*args, **kw):
    l = apply(range, args, kw)
    l.reverse()
    return l

--
Robert Kern
kern at caltech.edu

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter



More information about the Python-list mailing list