[Tutor] Iterating over sorted dictionary keys in one line
John Fouhy
john at fouhy.net
Mon Sep 19 00:13:50 CEST 2005
On 19/09/05, Marcin Komorowski <marcink at ieee.org> wrote:
> Is there a way to do this in a single line. Something like this would be
> ideal:
> for key in dictionary.keys().soft():
Hi Marcin,
Others have already answered you, but just to follow up:
There is a reason why lst.sort() returns None: When you call .sort()
on a list, you are changing the original list. If you happened to
have a reference to that list somewhere else in your program, sorting
it could cause unexpected behaviour. So, python deliberately prevents
you from being able to type "for item in lst.sort()" as a reminder
that there are side-effects that you need to be wary of.
On the other hand, the new sorted() function creates a sorted copy, so
it doesn't matter (but you should be aware of the extra memory
requirements if you have big lists).
--
John.
More information about the Tutor
mailing list