Pregunta

I was fooling around and stumbled on something I don't understand...

Question 1:

a = [1,2,3]
b = [1,2,3,4]

len(a) < b

The result is True, but is this actually comparing the length of the two lists? It seems to be since this is also True...

a = [15,32,7]
len(a) < b

Question 2:

What happens when we try comparing integers with lists? Why are these all True (I'm assuming there's a general explanation...)...

3 < b
20 < b
float('inf') < b
None < b
(lambda x: (x**x)**x) < b

...and these False?

'poo' < b
'0' < b
¿Fue útil?

Solución

In Python 2.x, items of dissimilar types which are not directly comparable are compared using the name of their types. So all integers are less than all lists, because "int" is less than "list". For the same reason all strs are greater than all ints and floats.

This unintuitive behavior (which I assume was introduced so that items of like type sort together in a heterogeneous list) was removed in Python 3, which raises an exception for these comparisons.

Otros consejos

From the docs on data types:

Sequence objects may be compared to other objects with the same sequence type. The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted.

And

Note that comparing objects of different types is legal. The outcome is deterministic but arbitrary: the types are ordered by their name. Thus, a list is always smaller than a string, a string is always smaller than a tuple, etc. 1 Mixed numeric types are compared according to their numeric value, so 0 equals 0.0, etc.

And, notably,

Footnotes 1 The rules for comparing objects of different types should not be relied upon; they may change in a future version of the language.

The other answers do a good job explaining what is happening, but the right way to compare the lengths is

len(a) < len(b)
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top