lang comparison: in-place algorithm for reversing a list in Perl, Python, Lisp
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Thu Mar 1 00:01:30 EST 2012
On Wed, 29 Feb 2012 20:07:49 -0800, Xah Lee wrote:
> Here's in-place algorithm for reversing a list:
>
> # python
> # in-place algorithm for reversing a list
>
> list_a = ["a", "b", "c", "d", "e", "f", "g"]
> list_length = len(list_a)
> for i in range(list_length/2):
> x = list_a[i]
> list_a[i] = list_a[ list_length -1 - i]
> list_a[ list_length -1 - i] = x
>
> print list_a
This is a good example of code written by somebody not very familiar with
Python idioms. You don't need a temporary variable to swap two values in
Python. A better way to reverse a list using more Pythonic idioms is:
for i in range(len(list_a)//2):
list_a[i], list_a[-i-1] = list_a[-i-1], list_a[i]
But the best way (even more idiomatic and much, much faster) is this:
list_a.reverse()
--
Steven
More information about the Python-list
mailing list