[Python-Dev] list.sorted()

Raymond Hettinger raymond.hettinger at verizon.net
Sat Dec 6 15:54:21 EST 2003

When working on itertools.groupby(), the tutorial updates, and
exercising the newer features, I've made frequent use of list.sorted().

The good news is that after using it many times, I no longer hate the
name ;-)  Also, it fits well inside list comps (and is expected to do
the same with gen exps) plus it works well with itertools.  In fact, it
is a delight to use.  One surprise use case was how nicely it works with
unittest.TestCase.assertEqual() when verifying that two collections are
equal with respect to permutation.

The bad news is that the list dot prefix adds no value, feels awkward,
and interferes with the eye's ability to parse expressions containing

Part of the reason for making it a classmethod was that it *is*
effectively an alternative constructor for lists.  OTOH, that could be
said for any function that returns a list.

The two disadvantages of having it as a classmethod are the mandatory
list dot prefix and that it is confusing when called with an existing

  [f(elem, arg) for elem in [3,2,1].sorted(anotherseq)]

It's up to someone else to propose the obvious solutions -- I've already
gone over my quota and am running low on asbestos ;-)

Whatever the answer, it's important that the result look clean when used
in gen exps or as an argument to functions expecting a sequence.

Raymond Hettinger

More information about the Python-Dev mailing list