user2080741
user2080741

Reputation: 11

unexpected result sorting list with mixed items tuples and lists

tmp = [
    (1, 2, 3),
    (4, 5, 6),
    [7, 8, 9],
    [10, 11, 12],
]

print tmp
tmp.sort()
print tmp

results in:

[(1, 2, 3), (4, 5, 6), [7, 8, 9], [10, 11, 12]]
[[7, 8, 9], [10, 11, 12], (1, 2, 3), (4, 5, 6)]

Apparently lists get precedence over tuples. Is this correct?

Upvotes: 0

Views: 66

Answers (1)

Lfa
Lfa

Reputation: 1069

In Python 2,

In the documentation https://docs.python.org/2/reference/expressions.html#not-in,

Most other objects of built-in types compare unequal unless they are the same object; the choice whether one object is considered smaller or larger than another one is made arbitrarily but consistently within one execution of a program.

But I believe it's implementation independent:

Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.

In Python 3, this is fixed, so that comparing tuples and lists gives

TypeError: unorderable types: tuple() > list().

Upvotes: 3

Related Questions