[issue7257] Improve documentation of list.sort and sorted()

Ole Laursen report at bugs.python.org
Tue Nov 3 19:03:22 CET 2009


New submission from Ole Laursen <olau at iola.dk>:

On my Python 3.1, help() for sorted returns

sort(...)
    L.sort(key=None, reverse=False) -- stable sort *IN PLACE*

sorted(...)
    sorted(iterable, key=None, reverse=False) --> new sorted list

Kindly suggest this be expanded. Here's some text:

sort(...)

Sorts the sequence with a fast stable sort. The sequence is modified in
place. To remind you of this, the function always returns None. Example:

a = [1, 3, 2]
a.sort()
# a is now [1, 2, 3]

Use the "sorted()" built-in function if you need to preserve the
original list.

Set "reverse" to True to sort the elements in reverse order. A function
for extracting a key for comparison from each object can be passed in as
"key", e.g.

a = [{'k': 'foo'}, {'k': 'bar'}]
a.sort(key=lambda x: x['k'])
# a is now [{'k': 'bar'}, {'k': 'foo'}]

Note that "key" can be used to solve many sorting problems, e.g.
key=str.lower can be used for case-insensitive sorting and key=lambda x:
(x['a'], x['b']) can be used to sort by first 'a' then 'b'.

The sort is stable which means that the relative order of elements that
compare equal is not changed.


sorted(...)

Sorts the sequence with a fast stable sort and returns a new list with
the result. Example:

[same text as before]


I'm not sure how this interacts with what's in the online help
(http://docs.python.org/3.1/library/stdtypes.html search for "sort("),
maybe the text could just be copied over. I think it's important to give
copy-pasteable examples for something as important as this, and hint at
how you solve common sorting problems.

----------
assignee: georg.brandl
components: Documentation
messages: 94863
nosy: georg.brandl, olau
severity: normal
status: open
title: Improve documentation of list.sort and sorted()

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue7257>
_______________________________________


More information about the Python-bugs-list mailing list