4

Possible Duplicate:
How does Python compare string and int?

An intern was just asking me to help debug code that looked something like this:

widths = [image.width for image in images]
widths.append(374)
width = max(widths)

...when the first line should have been:

widths = [int(image.width) for image in images]

Thus, the code was choosing the string '364' rather than the integer 374. How on earth does python compare a string and an integer? I could understand comparing a single character (if python had a char datatype) to an integer, but I don't see any straightforward way to compare a string of characters to an integer.

Community
  • 1
  • 1
Jason Baker
  • 192,085
  • 135
  • 376
  • 510

3 Answers3

11

Python 2.x compares every built-in type to every other. From the docs:

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).

This "arbitrary order" in CPython is actually sorted by type name.

In Python 3.x, you will get a TypeError if you try to compare a string to an integer.

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

When comparing values of incompatible types in python 2.x, the ordering will be arbitrary but consistent. This is to allow you to put values of different types in a sorted collection.

In CPython 2.x any string will always be higher than any integer, but as I said that's arbitrary. The actual ordering does not matter, it is just important that the ordering is consistent (i.e. you won't get a case where e.g. x > y and y > z, but z > x).

sepp2k
  • 363,768
  • 54
  • 674
  • 675
0

From the documentation:

Most other objects of built-in types compare unequal unless they are the same object; the choice whether one object is considered smaller or larger than another one is made arbitrarily but consistently within one execution of a program

Hope this is clear enough - like it has been said, it is arbitrary.

Tadeck
  • 132,510
  • 28
  • 152
  • 198
  • It seems to be arbitrary & consistent on one platform, but when I move the code to another platform the order can change. – dbn Jan 18 '13 at 19:49