2

I tried this in python shell

>>> a='apple'
>>> b=11.1
>>> a>b
True
>>> a
'apple'
>>> b>a
False

Can someone explain to me how a>b is True? When a is an string and b is float.

Gareth Rees
  • 64,967
  • 9
  • 133
  • 163
Gaurav Agarwal
  • 18,754
  • 29
  • 105
  • 166

2 Answers2

5

Order comparison between elements of different types was a "design bug" in Python 2.x that has been removed in Python 3 (where you get a runtime error).

Correcting it wasn't an option before 3.x because of a lot of existing software that does sorting on heterogeneous containers (and version 3 is the first in which backward compatibility is intentionally broken).

In Python 2.x you can compare anything for </>, with the only exception of complex numbers where this is explicitly forbidden.

The ordering result of comparison of different types is arbitrary but fixed at least for a given run of the Python interpreter, see http://docs.python.org/2/reference/expressions.html#not-in . Values of different non-numeric types are always considered different.

6502
  • 112,025
  • 15
  • 165
  • 265
  • 1
    Putting it in simple terms It is bug in 2.x, gives quite random results and removed from 3.x – Gaurav Agarwal Oct 31 '13 at 18:08
  • 1
    @GauravAgarwal: "random" is excessive, it's arbitrary (e.g. if `'a'<3` then any string is less than any integer) and you can for example implement a sorting because you get transitivity. It was a design bug that could not be fixed before python 3.x because people started depending on it. – 6502 Oct 31 '13 at 18:12
1

In Python 2, comparison between incomparable types often "works", giving meaningless results. Sometimes it's fun: 'aleph0' > float('+inf'). But most of the time it's just silly.

So Python 3 has removed this, and 'a' > 1.0 quite reasonably raises a TypeError under it.

9000
  • 39,899
  • 9
  • 66
  • 104