Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange comparisons in Python [duplicate]

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
like image 908
myedibleenso Avatar asked Sep 16 '25 11:09

myedibleenso


1 Answers

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.

like image 181
kindall Avatar answered Sep 18 '25 10:09

kindall