I recently discovered a typo in my program
while len(first_list) > second_list:
do_stuff
I played around with this and discovered that 5 < ["apple"] == True
and 5 > ["apple"] == False
Why does Python allow these sorts of comparisons? What is being evaluated under the hood to determine that 5
is less than ["apple"]
?
The cmp() function is a built-in method in Python used to compare the elements of two lists. The function is also used to compare two elements and return a value based on the arguments passed. This value can be 1, 0 or -1.
We can club the Python sort() method with the == operator to compare two lists. Python sort() method is used to sort the input lists with a purpose that if the two input lists are equal, then the elements would reside at the same index positions.
Another approach to find, if two lists have common elements is to use sets. The sets have unordered collection of unique elements. So we convert the lists into sets and then create a new set by combining the given sets. If they have some common elements then the new set will not be empty.
I think that the types are compared in this case, so it's like writing:
type(5) < type(["apple"])
and since "int" and "list" are compared lexicographically ("i" < "l"), you're getting this output.
If you try:
"5" > ["apple"]
you'll get False, since "string" > "list".
Documentation:
CPython implementation detail: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.
Its from documentation of python 2:
The operators
<
,>
,==
,>=
,<=
, and!=
compare the values of two objects. The objects need not have the same type. If both are numbers, they are converted to a common type. Otherwise, objects of different types always compare unequal, and are ordered consistently but arbitrarily. You can control comparison behavior of objects of non-builtin types by defining a__cmp__
method or rich comparison methods like__gt__
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With