about sort and dictionary

Magnus Lycka lycka at carmen.se
Mon Nov 21 12:35:13 EST 2005


bonono at gmail.com wrote:
> most built-in function/method don't return the "object" but None. This
> I believe is the language creator's preference for everything being
> explicit. 

The list methods .sort() and .reverse() don't create copies,
but rather change the existing object. The reson for this is
to save RAM. If you have 512MB RAM and a 300 MB list, it's
nice that you can sort it without swapping virtual memory to
disk. That would slow down the sort operation a lot, and that
would be a shame, considering all the efforts that went into
Python's excellent sort implementation.

If you sort (or reverse) a list l, and don't need to keep the
unsorted list, you simply do l.sort() (or l.reverse()). If
you need to keep the original as well, you must make a copy
before the sort, like this: sorted_l = l[:]; sorted_l.sort().

If the sort operation had returned self, it would have been
easy to write:

sorted_l = l.sort()

and while sorted_l would contain what one might expect, it
would in fact just be another name referencing exactly the
same sorted list as l, and it would probably be surprising
that l was also sorted, and that subsequent changes would
show up in both sorted_l and l, and that sorted_l might not
be sorted and longer even though you only modified l. It's
this particular gotcha that the language creator wanted to
avoid.

With newer versions of Python, the builtin functions sorted()
and reversed() have been added, so those who think it's ugly
to call a list sorted before it actually *is* sorted, can
simply write:

sorted_l = sorted(l)

With older Python's you need to do the hard work to add this
to your program:

def sorted(l): s=l[:];s.sort();return s
def reversed(l): r=l[:];r.reverse();return r

Actually, I guess it's possible that sorted() is done so
that it works like below, but I don't think pre-sorted()
versions of Python support keyword arguments to list.sort()
anyway...

def sorted(l, *p, **kw): s=l[:];s.sort(*p, **kw);return s



More information about the Python-list mailing list