list.reverse()

blaine frikker at gmail.com
Tue Apr 29 09:39:53 EDT 2008


On Apr 29, 9:32 am, Roy Smith <r... at panix.com> wrote:
> In article <4816e26a$0$30938$426a7... at news.free.fr>,
>  Bruno Desthuilliers <bruno.42.desthuilli... 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().
>
> >>> range(5)
>
> [0, 1, 2, 3, 4]
>
> >>> reversed(range(5))
>
> <listreverseiterator object at 0x6f8d0>
>
> >>> list(reversed(range(5)))
>
> [4, 3, 2, 1, 0]
>
> >>> for i in reversed(range(5)):
>
> ...     print i
> ...
> 4
> 3
> 2
> 1
> 0
>
>

Check out this cool little trick I recently learned:
>>> x=range(5)
>>> x.reverse() or x
[4, 3, 2, 1, 0]

Useful for returning lists that you need to sort or reverse without
wasting that precious extra line :)

What it does: x.reverse() does the reverse and returns None.  or is
bitwise, so it sees that 'None' is not 'True' and then continues to
process the next operand, x.  x or'd with None will always be x (and x
has just been changed by the reverse()).  So you get the new value of
x :)

Blaine



More information about the Python-list mailing list