Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string to integer comparison in Python [duplicate]

Tags:

python

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

like image 779
Varun Avatar asked Nov 30 '25 22:11

Varun


1 Answers

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.

like image 93
phihag Avatar answered Dec 03 '25 11:12

phihag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!