Paul Prescod paulp at
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!!!

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()
	for key in keys: whatever with dict[key]...

Take a recipe. Leave a recipe.  
Python Cookbook!

More information about the Python-list mailing list