hynekcer
hynekcer

Reputation: 15548

Python 2.x sorted puzzlement

I have a partially sorted tuple in Python 2.x.

Why Python reverse it instead of sort it?

>>> data = (u'a', (1,), 'b ', u'b', (2,), 'c ', u'c', (3,), 'd ', u'd', (4,), 'e')
>>> sorted(data) == list(reversed(data))
True

I look forward to Python 3.

Upvotes: 2

Views: 158

Answers (1)

Deestan
Deestan

Reputation: 17136

It fails because the sorting algorithm depends on a total ordering of the elements, which implies transitive <.

The ordering of unicode strings, tuples, and strings isn't transitive:

>>> a = 'x'
>>> b = (1,)
>>> c = u'x'
>>> a < b
True
>>> b < c
True
>>> a < c
False

I.e., there exists no valid sort for your list. At least not with the default comparator.

Upvotes: 11

Related Questions