lang comparison: in-place algorithm for reversing a list in Perl, Python, Lisp

Dan Stromberg drsalists at gmail.com
Thu Mar 1 06:05:06 CET 2012


On Wed, Feb 29, 2012 at 8:07 PM, Xah Lee <xahlee at gmail.com> wrote:

> fun example.
>
> in-place algorithm for reversing a list in Perl, Python, Lisp
> http://xahlee.org/comp/in-place_algorithm.html
>
> plain text follows
> ----------------------------------------
>
> What's “In-place Algorithm”?
>
> Xah Lee, 2012-02-29
>
> This page tells you what's “In-place algorithm”, using {python, perl,
> emacs lisp} code to illustrate.
>
> Aren't in-place reversals rather non-functional?


> Python
>
The usual way is list_a.reverse().  This is in place.

If you want to be a little weird, you could do this, but it's not in place:
list_a = list_a[::-1]

If you want to pretend you can't do this the easy ways above, you could do
this, which is in place:
length = len(list_a)
for ind in xrange(length // 2):
   other=-ind-1
   list_a[ind], list_a[other] = list_a[other], list_a[ind]

HTH
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20120229/935b64d0/attachment.html>


More information about the Python-list mailing list