How python compares strings and integers

In the following code, this is a simple algorithm written to sort items. The question is, how do strings compare inside and how does the interpreter know that these strings should be placed after 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'] 
+4
source share
2 answers

In 2.x, if two objects cannot be forced to a common type, it compares class names. "str"> "int", so they come after.

In 3.x, if two objects cannot be forced to a common type, an exception is thrown.

+3
source

Arbitrarily.

Objects of different types, except for different numeric types and different types of strings, never compare the same; such objects are ordered sequentially, but arbitrarily (so that sorting a heterogeneous array gives a consistent result). In addition, some types (for example, file objects) support only the degenerate concept of comparison, where any two objects of this type are unequal. Again, such objects are ordered randomly, but sequentially . The operators <, <=,> and> = will throw a TypeError exception if any operand is a complex number.

From Built-in Types (Python.org)

+2
source

Source: https://habr.com/ru/post/1396772/


All Articles