How does python compare strings and integers

Question:

In the following code below this is a simple algorithm written to sort the elements.My question is that how are strings are compared internally and how the interpreter knows that these strings are to be placed after the integers

a=[22, 66, 54, 11, 16, 2, 5, 'b', 'a', 3, 2, 1] 
>>> for i in range(len(a)-1):
...    for j in range(len(a)-i-1):
...       if a[j] > a[j+1]:
...          a[j],a[j+1]=a[j+1],a[j]
...
>>> print a
[1, 2, 2, 3, 5, 11, 16, 22, 54, 66, 'a', 'b']
Asked By: Rajeev

||

Answers:

In 2.x, if the two objects cannot be coerced to a common type then it compares the class names. “str” > “int”, so they come after.

In 3.x, if the two objects cannot be coerced to a common type then an exception is raised.

Arbitrarily.

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). Furthermore, some types (for example, file objects) support only a degenerate notion of comparison where any two objects of that type are unequal. Again, such objects are ordered arbitrarily but consistently. The <, <=, > and >= operators will raise a TypeError exception when any operand is a complex number.

From Built-In Types (Python.org)

Answered By: Tim
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.