The Python Oracle

Why is tuple larger than a list in python?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game Looping

--

Chapters
00:00 Why Is Tuple Larger Than A List In Python?
00:32 Accepted Answer Score 4
02:04 Answer 2 Score 2
02:44 Answer 3 Score 1
03:28 Answer 4 Score 0
03:47 Answer 5 Score 0
04:16 Thank you

--

Full question
https://stackoverflow.com/questions/2099...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #python27

#avk47



ACCEPTED ANSWER

Score 4


From the docs:

The operators <, >, ==, >=, <=, and != compare the values of two objects. The objects need not have the same type. If both are numbers, they are converted to a common type. Otherwise, objects of different types always compare unequal, and are ordered consistently but arbitrarily. You can control comparison behavior of objects of non-builtin types by defining a __cmp__ method or rich comparison methods like __gt__, described in section 3.4.

(This unusual definition of comparison was used to simplify the definition of operations like sorting and the in and not in operators. In the future, the comparison rules for objects of different types are likely to change.)

Which is true. In python 3 this is a TypeError.

() > []
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-d2326cfc55a3> in <module>()
----> 1 () > []

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

Back to python 2: The docs stress that this is an arbitrary, but consistent ordering.

In cPython 2, unequal types are compared by their type name. So tuple is "greater than" list, lexicographically.




ANSWER 2

Score 2


This is a CPython (2.x) implementation detail, as documented in Built-in Types - Comparisons:

CPython implementation detail: 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.

Therefore, any tuple compares greater than any list because 'tuple' > 'list'.

This no longer holds in CPython 3, and has never held for other implementations of Python 2.x.




ANSWER 3

Score 0


This could be implementation dependent and I think there is no direct reason for this. Python 3.X prohibits comparison between two different Types all together.




ANSWER 4

Score 0


This is, because python 2.x uses the method __cmp__().
Python 3.x won't use this method.

You are using a python version lower than 3.0.
With python version 3.x, there will be an exception:
TypeError: unorderalbe types ...