Sorting a list with entries of unequal types

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Jan 29 02:24:33 CET 2010


On Fri, 29 Jan 2010 12:13:50 +1100, Ben Finney wrote:

> Paul Rubin <no.email at nospam.invalid> writes:
> 
>> Ben Finney <ben+python at benfinney.id.au> writes:
>> > So how should I be sorting a list with entries of “unequal types”
>> > such that it will work in Python 3?
>>
>> Um, what ordering do you want?
> 
> The same ordering I'd get in Python 2; that is, determined by the types
> of the elements.

The ordering has not been consistent across minor versions of Python 2:


$ python2.0
Python 2.0.1 (#1, Jan 14 2010, 15:43:17)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2
Type "copyright", "credits" or "license" for more information.
>>> L = [None, {}, [], 1, "x"]
>>> L.sort()
>>> L
[1, None, {}, [], 'x']


$ python2.6
Python 2.6.1 (r261:67515, Dec 24 2008, 00:33:13)
[GCC 4.1.2 20070502 (Red Hat 4.1.2-12)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> L = [None, {}, [], 1, "x"]
>>> L.sort()
>>> L
[None, 1, {}, [], 'x']


Python has never guaranteed a particular ordering for unequal types, only 
that it would be consistent between repeated calls to sort.


-- 
Steven



More information about the Python-list mailing list