2

Possible Duplicate:
How does Python compare string and int?

I had a Python script that wasn't evaluating two values as expected. The value '10' was determined as being greater than 200. The issue was the variable holding the value of '10' was actually a string and not an integer (whereas 200 was an integer).

My question is:

What is the process Python goes through when evaluating a string against an integer? How does it make the comparison?

For example:

string="10"
int=200
if string >= int:
  print("String is greater")
else:
  print("Int is greater")

Would output:

String is greater

Why is this? I would have thought Python would just exit with an error when trying to compare the two types.

Community
  • 1
  • 1
Rauffle
  • 957
  • 2
  • 8
  • 14
  • It's even better when they're both strings, and `"10" < "200"` is true, but for the wrong reason, which makes it impossible to throw an error and really confuses you when you do `"20" < "100"`. Moral of the story: know what type your objects are :) – Wooble Jul 26 '12 at 17:05

3 Answers3

5

Python 2.x allows comparing objects of any type, and guarantees that results are reprroducible. In Python 3.x, comparing objects that cannot be ordered meaningfully results in an error. The rationale for the 2.x behaviour was that it is sometimes convenient to be able to list.sort() heterogeneous lists. The rationale for the new 3.x behaviour is that the old behaviour hid errors.

The ordering used by Python 2.x is an implementation detail. CPython uses some rather strange rules, roughly

NoneType < numbers < old-style classes, ordered by name < new-style classes, ordered by name

(No guarantees that I got this right, but I won't bother to check. It's an implemetation detail, don't rely on it.)

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
4

In Python 3, you do get a TypeError when trying to compare a string and int (or any 2 uncomparable types).

In Python 2, the behavior is implementation-specific; in cPython, the names of the types usually end up getting compared (although you probably shouldn't rely upon this...), so strings are always greater than integers.

Wooble
  • 87,717
  • 12
  • 108
  • 131
2

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.

Daniel DiPaolo
  • 55,313
  • 14
  • 116
  • 115