Immutable list reverse function

Nick Perkins nperkins7 at home.com
Fri Jul 20 03:57:24 EDT 2001


"Martin Sjögren" <martin at strakt.com> wrote in message


...
What I want to do is basically this:
>>> foo(reverse(create_a_list()))
...

you could write your own function like this:

def myreverse(List):
    revlist = List[:]  # make a copy of the list
    revlist.reverse()  # reverse the copy
    return revlist     # return the reversed copy


>>> foo(myreverse(create_a_list()))

This works the way you want, but is a bit wasteful, since the list created
by create_a_list() will be lost and garbage collected, leaving you with the
reversed copy.  Not a big deal, though, unless performance really matters.

If you wanted to keep a copy of the original, un-reversed list, then this
function would be just right.

A better option, if you don't want to keep an un-reversed list, is to do
this:

def myreverse(List):
    List.reverse()
    return List

Which will reverse the original list, without making a copy, and return a
reference to the reversed list:

Now this still works, but is more efficient because no copy is made.

>>> foo(myreverse(create_a_list()))







More information about the Python-list mailing list