Python 3.0 - is this true?

Terry Reedy tjreedy at
Sun Nov 9 05:00:27 CET 2008

Steven D'Aprano wrote:
> On Sat, 08 Nov 2008 19:02:28 +0000, Arnaud Delobelle wrote:
>>> And, if so, why are they doing this?
>> How is it helpful to be able to sort things which have no natural order?
> Assuming you need to sort arbitrary types, then you have to choose an 
> order, even if it is arbitrary, so long as it's consistent.
> I agree that Python shouldn't try to guess how to order incomparable 
> types, nor how to order unorderable types, but I'm pretty sure that by 
> using the key argument to sort you can specify your own ordering. I don't 
> have Python 3 installed here, but some variation on this will probably 
> work:
>>>> alist = [2+3j, -4+5j, 8+2j, 1-7j, 6]
>>>> sorted(alist, key=str)
> [(-4+5j), (1-7j), (2+3j), (8+2j), 6]

> Define your own ordering if you need to sort incomparable types.

Yes, key= lets you sort anything anyway you want.
 >>> l=[1, '2', 3j]
 >>> sorted(l, key = str)
[1, '2', 3j]
 >>> sorted(l, key = id)
['2', 3j, 1]

More information about the Python-list mailing list