list.sort()

Paul Prescod paulp at ActiveState.com
Sun Jun 17 22:16:24 CEST 2001


Charlie Dyson wrote:
>...
> 
> Hmm, I actually think that this behaviour is not very logical. Concider:
> 
> x = {'Python' : 'Cool', 'Linux' : 'Cool'}
> print x.keys().sort() # Prints None
> 
> It would be better if it sort **returned** the results, instead 
> I have to
> do:
> keys = x.keys()
> keys.sort()
> 
> That's one extra line of code!!!

http://www.python.org/doc/FAQ.html#6.20

6.20. Why doesn't list.sort() return the sorted list?

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. 

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

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

-- 
Take a recipe. Leave a recipe.  
Python Cookbook!  http://www.ActiveState.com/pythoncookbook




More information about the Python-list mailing list