This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: General FAQ: list.sort() out of date
Type: Stage:
Components: None Versions:
process
Status: closed Resolution: accepted
Dependencies: Superseder:
Assigned To: jlgijsbers Nosy List: jlgijsbers, tcdelaney
Priority: normal Keywords:

Created on 2005-01-03 23:16 by tcdelaney, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Messages (4)
msg23861 - (view) Author: Tim Delaney (tcdelaney) Date: 2005-01-03 23:16
http://www.python.org/doc/faq/general.html#why-
doesn-t-list-sort-return-the-sorted-list

specifies the idiom:

keys = dict.keys()
keys.sort()
for key in keys:
        ...do whatever with dict[key]...

and doesn't mention sorted().

I would suggest the following wording be used:

In situations where performance matters, making a copy 
of the list just to sort it would be wasteful. Therefore, 
list.sort() sorts the list in place. In order to remind you 
of that fact, it does not return the sorted list. This way, 
you won't be fooled into accidentally overwriting a list 
when you need a sorted copy but also need to keep the 
unsorted version around.

In Python 2.4 a new builtin - sorted() - has been added. 
This function creates a new list from the passed 
iterable, sorts it and returns it.

As a result, here's the idiom to iterate over the keys of a 
dictionary in sorted order:

for key in sorted(dict.iterkeys()):
        ...do whatever with dict[key]...
msg23862 - (view) Author: Tim Delaney (tcdelaney) Date: 2005-01-03 23:21
Logged In: YES 
user_id=603121

Do we want to also reference the 2.3 and earlier idiom?
msg23863 - (view) Author: Tim Delaney (tcdelaney) Date: 2005-01-04 00:28
Logged In: YES 
user_id=603121

Updated text:

In situations where performance matters, making a copy 
of the list just to sort it would be wasteful. Therefore, 
list.sort() sorts the list in place. In order to remind you 
of that fact, it does not return the sorted list. This way, 
you won't be fooled into accidentally overwriting a list 
when you need a sorted copy but also need to keep the 
unsorted version around.

In Python 2.4 a new builtin - sorted() - has been added. 
This function creates a new list from a passed 
iterable, sorts it and returns it.

As a result, here's the idiom to iterate over the keys of a 
dictionary in sorted order:

for key in sorted(dict.iterkeys()):
    ...do whatever with dict[key]...

Versions of Python prior to 2.4 need to use the following idiom:

keys = dict.keys()
keys.sort()
for key in keys:
    ...do whatever with dict[key]...
msg23864 - (view) Author: Johannes Gijsbers (jlgijsbers) * (Python triager) Date: 2005-01-08 12:41
Logged In: YES 
user_id=469548

Fixed in rev 1.22 of general.ht. Thanks for the new text!
History
Date User Action Args
2022-04-11 14:56:08adminsetgithub: 41392
2005-01-03 23:16:48tcdelaneycreate