roy at panix.com
Tue Apr 29 15:32:46 CEST 2008
In article <4816e26a$0$30938$426a74cc at news.free.fr>,
Bruno Desthuilliers <bruno.42.desthuilliers at websiteburo.invalid> wrote:
> Mark Bryan Yu a écrit :
> > This set of codes works:
> >>>> x = range(5)
> >>>> x.reverse()
> >>>> x
> > [4, 3, 2, 1, 0]
> > But this doesn't:
> >>>> x = range(5).reverse()
> >>>> print x
> > None
> This works just as expected - at least for anyone having read the doc.
> > Please explain this behavior. range(5) returns a list from 0 to 4 and
> > reverse just reverses the items on the list that is returned by
> > range(5). Why is x None (null)?
> Because that's what list.reverse() returns. Call it a wart if you want
> (FWIW, I do), but at least that's well documented.
The reasoning goes along the lines of, "reverse in place is an expensive
operation, so we don't want to make it too easy for people to do". At
least that's the gist of what I got out of the argument the many times it
has come up.
And, yes, I agree with Bruno that it's a wart.
What you want to do is look at the reversed() function. Not only does it
return something (other than Null), but it is much faster because it
doesn't have to store the reversed list anywhere. What it returns is an
iterator which walks the list in reverse order. If you really want it as a
list, you can turn it into one (with the list() constructor), or you can
just iterate over it with a for loop.
Same with list.sort() vs. the global sorted().
[0, 1, 2, 3, 4]
<listreverseiterator object at 0x6f8d0>
[4, 3, 2, 1, 0]
>>> for i in reversed(range(5)):
... print i
More information about the Python-list