2

I noticed that, much to my surprise, that

a = [1,2,3]
a > 8
Out[8]: 
True
a = [1,2,3,4,5,6,7,8,9,10,11,12]
a>8
Out[10]: 
True
[]>8
Out[11]: 
True

why is this the case? what is this operation actually doing? I also tried with lists of string with arbitrarily large numbers, they all came back true.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
Lost1
  • 990
  • 1
  • 14
  • 34
  • 1
    ISTR seeing somewhere that this was deliberate - that ordering was intended to separate items by type if comparison wasn't meaningful. Duck is not my friend today, so I haven't found it again. – aghast Feb 20 '19 at 16:27

2 Answers2

2

One could think Python 2 compares names alphabetically:

print(list>int)  # True
print(set>list)  # True
print(float<int) # True

until you try

print(dict<list) # False 

Then you need to read the documentation: comparisons

Objects of different types, except different numeric types and different string types, never compare equal; such objects are ordered consistently but arbitrarily (so that sorting a heterogeneous array yields a consistent result). Furthermore, some types (for example, file objects) support only a degenerate notion of comparison where any two objects of that type are unequal.

Again, such objects are ordered arbitrarily but consistently. The <, <=, > and >= operators will raise a TypeError exception when any operand is a complex number.

(emphasis mine)

This allows your to do:

k = [ 1, "a", 'c', 2.4, {1:3}, "hallo", [1,2,3], [], 4.92, {}]  # wild mix of types
k.sort()  # [1, 2.4, 4.92, {}, {1: 3}, [], [1, 2, 3], 'a', 'c', 'hallo'] type-sorted

In python 3 you get

TypeError: '>' not supported between instances of ... and ...


Community
  • 1
  • 1
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
-1

I am not really sure about the answer but I think it may be size (in terms of how much memory does this object occupies) comparison.

Try this:

import sys
sys.getsizeof([])
> 72
a = [1,2,3]
sys.getsizeof(a)
> 96

If you would like to do such list comparison you should do more or less like that:

a = [1, 2, 3]
sum(a) > 8
> False
hikamare
  • 304
  • 1
  • 14