Help understanding the decisions *behind* python?
steven at REMOVE.THIS.cybersource.com.au
Wed Jul 22 02:40:16 EDT 2009
On Tue, 21 Jul 2009 00:39:24 +0200, Niels L. Ellegaard wrote:
> Phillip B Oldham <phillip.oldham at gmail.com> writes:
>> We often find we need to do manipulations like the above without
>> changing the order of the original list, and languages like JS allow
>> this. We can't work out how to do this in python though, other than
>> duplicating the list, sorting, reversing, then discarding.
I think Phillip is confused if he thinks that other languages can sort a
list without modifying or duplicating the original. If you don't
duplicate the list, how can you sort it without modifying the original?
The only difference is whether the language makes the duplicate for you,
or expects you to do it yourself.
> If you just want a one-liner, and you don't care about speed you can do
> the following (but I don't think this is considered best practice)
>>>> x = [2,1,3]
>>>> print list(sorted(x))
The call to list is redundant, as sorted() already creates a list.
But that's the wrong solution to the problem. The OP wants the largest
(or smallest) item, which he expects to get by sorting, then grabbing the
That requires sorting the entire list, only to throw away everything
except the first item. A better solution is to use min() and max(),
neither of which sort the list, so they are much faster.
More information about the Python-list