3

Possible Duplicate:
How does Python compare string and int?

I was doing some comparison in Python. I was surprised to see that I can compare a string to an integer. then I did an id and found out that actually id for string is greater than id for int and i thought that's the reason I am getting this output.

In [19]: 'a' < 3
Out[19]: False

In [20]: 'a'>3
Out[20]: True

In [17]: id('a')
Out[17]: 140414909035824

In [18]: id(3)
Out[18]: 23119752

Please confirm that I am interpreting this behavior correctly (Python comparing on id level).

Community
  • 1
  • 1
Varun
  • 1,013
  • 3
  • 17
  • 28
  • 1
    Yes it is correct for python 2 but not python 3, this question has been asked before. – jamylak May 05 '12 at 12:14
  • Duplcate: http://stackoverflow.com/questions/3270680/how-does-python-compare-string-and-int – rubik May 05 '12 at 12:15
  • Thanks, so because string has more words than int,that's why string is greater than int in question above. – Varun May 05 '12 at 12:18
  • If you read the duplicate post you can see, it says 'different types are compared by the name of their type'. Not sure what you mean by words, but whichever type of word you mean doesn't matter. – jamylak May 05 '12 at 12:21

1 Answers1

5

Python 2.x's cross-type comparisons are a historical accident. From the documentation:

(...) objects of different types always compare unequal, and are ordered consistently but arbitrarily

In Python 3.x, this is fixed - these comparisons throw a type error.

phihag
  • 278,196
  • 72
  • 453
  • 469
  • I am very new to Python (programming itself), do you thing that in this case I should start with Python 3 instead of Python 2? – Varun May 05 '12 at 12:20
  • It's probably best to stick with Python 2 IMO as there are more resources available for it. – jamylak May 05 '12 at 12:23
  • Yes, definitely. Python 3 is much cleaner in a number of aspects. The only reason anybody is using Python 2 at the moment is its prevalence and a larger number of libraries. Neither matters when you're learning a new language, or programming. – phihag May 05 '12 at 12:23